Jump to content

User:Theopolisme/whisperbackLink.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
//<nowiki>
// Based on code from [[User:Writ_Keeper/Scripts/talkbackLink.js]]
function talkbackLink() {
	if($("#mw-content-text").length > 0) {
		var $nodeList = $('a[title^="User talk:"]'), pdne = ' (page does not exist)';
		if($nodeList !== null) {
			var i;
			for( i = 0; i < $nodeList.length; i++) {
				var $link = $($nodeList[i]);
					$newLink = $('<a href="#' + $link[0].title.replace(pdne, "") + '" style="font-size:x-small; display:inline-block;" title="Send a whisperback!" noPopup=1 id="TBsubmit' + i + '">TB</a>');
				$newLink.click(function(e) {
					tbSubmit($(this).attr('href').substr(1), this.id)
				});
				$($link).after($newLink);
			}
		}
	$('a[title="Send a whisperback!"]').tipsy({html: true}).before("|").after("|");
	}
}
function tbSubmit(page, id) {
	var questionTitle = prompt("Please enter the title of the section you're replying in (or just leave it blank):", ""),sectionTitle ="{{wb|"+mw.config.get("wgUserName");
	if (questionTitle === null) {
		 $("#"+id).attr("title", 'You canceled the whisperback!').tipsy("show");
		 return;
	}
	else if (questionTitle === "") {
		sectionTitle += "}} ~~~~~";
	} 
	else {
		sectionTitle += "|" + questionTitle + "}} ~~~~";
	}
	var data = {
		format : 'json',
		action : 'edit',
		minor : false,
		title : page,
		text : sectionTitle,
		section : 'new',
		summary : (questionTitle === "") ? "Whisperback" : questionTitle,
		token : mw.user.tokens.get('editToken')
	};
	$.ajax({
		url : mw.util.wikiScript('api'),
		type : 'POST',
		dataType : 'json',
		data : data,
		success : function(data) {
			if(data && data.edit && data.edit.result && data.edit.result === 'Success') {
				//window.location = mw.util.getUrl(page);
                                alert("Whisperback posted!");
			} else {
				$("#"+id).attr("title", 'There was an error requesting the page edit. Code: ' + data.error.code + '": ' + data.error.info).tipsy("show");
			}
		},
		error : function() {
			$("#"+id).attr("title", 'There was an error using AJAX to edit the page.').tipsy("show");
		}
	});
}
if( mw.config.get('wgCanonicalNamespace') !== "Article" && mw.config.get('wgIsArticle')
	&& !(mw.config.get('wgCanonicalNamespace') === "User_talk" 
		&& mw.config.get('wgTitle').search("/") > -1)
	&& mw.config.get('wgPageName') !== "Wikipedia:Teahouse/Questions"
) {
	mw.loader.using( ['jquery.tipsy', 'mediawiki.util', 'mediawiki.user'], function () { $(talkbackLink); } );}
//</nowiki>