Wiktionary:User scripts/Snippets

Here are the list of snippets that are proof of concepts. They are supposed to be useful for creators.

Get wikitext edit

pageTitle is a fully qualified name.

function get_wikitext(pageTitle) {
	var wikitext = "";
	$.ajax({
		url: mw.util.wikiScript( 'index' ),
		data: {
			action:	 'raw',
			title: pageTitle
		},
		type: 'GET',
		success: function( result ) {
			wikitext = result;
		},
		error: function( xhr ) {
			alert( 'Error.\nRequest failed.' );
		},
		async: false
	});
	return wikitext;
}

Editing page edit

function addNewSection( pageTitle, summary, content, editToken ) {
	$.ajax({
		url: mw.util.wikiScript( 'api' ),
		data: {
			format: 'json',
			action: 'edit',
			title: pageTitle,
			section: 'new',
			summary: summary,
			text: content,
			token: editToken
		},
		dataType: 'json',
		type: 'POST',
		success: function( data ) {
			if ( data && data.edit && data.edit.result == 'Success' ) {
				window.location.reload(); // reload page if edit was successful
			} else if ( data && data.error ) {
				alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
			} else {
				alert( 'Error: Unknown result from API.' );
			}
		},
		error: function( xhr ) {
			alert( 'Error: Request failed.' );
		}
	});
}

Current pageTitle can be obtained by mw.config.get( 'wgPageName' )

editToken can be obtained by mw.user.tokens.get('editToken') For more see mediawiki's API reference

LangName → LangCode edit

new LanguageUtilsAsync().GetWiktionaryCodeByCanonicalName("Georgian").then(function(langcode){
    //do something with langcode
});

LangCode → Canonical name edit

new LanguageUtilsAsync().GetCanonicalNameByWiktionaryCode("ka").then(function(langname){
    //do something with langname. Here it is "Georgian"
});