Jump to content

User:Inductiveload/Template autoloader.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Inductiveload (talk | contribs) at 00:48, 6 November 2010. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
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.
/*
 * Grabs text from a Template documentation page that is wrapped in
 * <pre id="autoload_template"></pre> tags and inserts it into the document
 *
 * The aim of this is to allow users to easily insert blank templates into
 * pages and save thm looking up the parameters names and/or orders
 *
 * There is two way to use it, for both add
 * importScript('User:Inductiveload/Autoload template.js');
 * to your javascript.
 *
 * then add a link in the left regex menu, add to your .js
 * regexTool('Autoload template', 'autoloadTemplate()');
 */

function get_autoload_data(data)
{
    try {
        //the textbox to insert the text into
        var textbox = document.getElementsByName('wpTextbox1')[0];


        if (textbox && !data.query.pages["-1"]) {
            for (var ids in data.query.pages) {
                var content = data.query.pages[ids].revisions[0]['*'];

                var r = new RegExp("\<pre id=\"autoload_template\">(.*)\</pre\>");
                var match = r.exec(content);

                if (match) {
                   var template_text = match[0];

                   // prepend the autoloaded text to the editbox content
                   // TODO: insert at cursor (possible?)
                   textbox.value = content + "\n"  + textbox.value

                }

                textbox.value = content + "\n"  + textbox.value

                break;
            }
        }
    }
    catch (err) { }
}

function create_script_obj(url)
{
    var scriptObj = document.createElement("script");
    scriptObj.setAttribute("type", "text/javascript");
    scriptObj.setAttribute("src", url);
    document.body.appendChild(scriptObj);
}

function getTemplateName()
{
    return "Infobox book"

}


function autoloadTemplate( )
{
    var name = getTemplateName()
    var pagename = 'Template:' + name;

    var url = wgServer + wgScriptPath
        + "/api.php" + "?action=query" + "&prop=revisions"
        + "&callback=get_autoload_data" + "&rvprop=content"
        + "&format=json" + "&titles=" + encodeURIComponent(pagename);

    create_script_obj(url);
}