Snippets/WriteInPage

From mediawiki.org

This snippet uses the API to add content to a page, or completely replace the content of a page.

The function uses mw.user.tokens.get, and should be executed only after loading mediawiki.user, e.g. by calling

mw.loader.using('mediawiki.user', callSomeFunction);

When adding content to a page, you can prepend the content at the beginning of the page, append it to the end of the page, or append it to the end of a section. Unfortunately, it is not possible to prepend the content at the beginning of a section: using the "prependtext" option with a section parameter will prepend the text _before_ the section, in effect appending it to the previous section.

The operation will create a new page if the "title" you pass to the function does not exist, and it depends on the user running the script having "write" access to the page.

The "section" parameter is the section number - and should be used only with "appendtext" option.

"option" can be left empty, or have one of the following values: 'text', 'appendtext' or 'prependtext'. setting it to "text" or leaving it unassigned (e.g. by passing only 3 parameters to the function) will replace the content of the page with "content".


function writeInPage(title, content, summary, option, section, success) {
	var param = {action: 'edit', 
		title: title, 
		summary: summary, 
		token: mw.user.tokens.get('editToken'),
		format: 'json'
	}
	param[option || 'text'] = content;
	if (section || section === 0)
		param.section = section;
	$.post(mw.util.wikiScript('api'), param, function() {
		if (typeof(success) === 'function')
			success();
	}); 
}