User:Bryan/EditPage.js
Jump to navigation
Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
Documentation for this user script can be added at User:Bryan/EditPage. |
//<source lang="javascript>
/*
Maintainer: [[:commons:User:Bryan]]
Copyright: (c) 2007 Bryan Tong Minh
License: Licensed under the terms of the MIT license.
Library to edit pages. Create an instance of EditPage,
use the textData variable to obtain the page text, and
save it using save().
Tested on:
* Mozilla Firefox 2.0.0.4
*/
function getToken(tokenName, text, def)
{
var re = new RegExp('value\\=\\"(.*?)\\" name\\=\\"' +
tokenName + '\\"');
var res = re.exec(text);
if (res)
return res[1];
else
return def;
}
function EditPage(pageTitle, onload)
{
this.pageTitle = pageTitle;
this.onload = onload;
var self = this;
var req = sajax_init_object();
req.open('GET', '/w/index.php?action=edit&title=' +
encodeURIComponent(this.pageTitle), true);
req.setRequestHeader('Cookie', document.cookie); //IE Fix
req.onreadystatechange = function ()
{
if (req.readyState == 4)
{
var text = req.responseText;
self.wpEditToken = getToken('wpEditToken', text, '');
self.wpEdittime = getToken('wpEdittime', text, '0');
self.wpStarttime = getToken('wpStarttime', text, '0');
self.wpAutoSummary = getToken('wpAutoSummary', text, '');
var re = new RegExp('\\<textarea[\\s\\S]*?id\\=\\"wpTextbox1\\"[\\s\\S]*?\\>([\\s\\S]*?)\\<\\/textarea\\>');
var el = document.createElement('div');
el.innerHTML = re.exec(text)[0];
self.textData = el.textContent;
self.onload();
}
};
req.send(null);
this.save = function (text, summary)
{
var postdata =
'wpTextbox1=' + encodeURIComponent(text) +
'&wpSummary=' + encodeURIComponent(summary) +
'&wpSave=Save+page&wpScrolltop=0&wpSection=&wpEditToken=' +
encodeURIComponent(this.wpEditToken) +
'&wpEdittime=' + this.wpEdittime + '&wpStarttime=' +
this.wpStarttime + '&wpAutoSummary=' + this.wpAutoSummary;
var req = sajax_init_object();
req.open('POST', '/w/index.php?action=submit&title=' +
encodeURIComponent(this.pageTitle), true);
req.setRequestHeader('Cookie', document.cookie); //IE Fix
req.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
req.setRequestHeader('Content-Length', postdata.length.toString());
req.send(postdata);
};
}
//</source>