User:Shardsofmetal/monobook.js/Autolink.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.
// <pre> This can be found at [[Wikipedia:WikiProject_User_scripts/Scripts/Autolink]]

// Autolink [[wikilinks]] and {{templates}} (especially useful for monobook.js and similar pages)

addOnloadHook(function () {
    // Get the HTML of just the main body of the page, not including textareas hopefully
    if (document.title.indexOf("Editing ") != 0 && document.title.indexOf("Template:") != 0) {
        targetdiv = document.getElementById('bodyContent');  // bodyContent div for most pages
    } else 
    if (document.getElementById('wikiPreview')) {
        targetdiv = document.getElementById('wikiPreview');  // wikiPreview if it's there
    } else
    if (document.getElementById('wikiDiff')) {
        targetdiv = document.getElementById('wikiDiff');   // wikiDiff if it's there
    } else {
        return;
    }
    content = targetdiv.innerHTML;
    content = content.replace(/([^\[])\[{2}([^\[\]\|\<\>\n]*)([^\[\]\<\>\n]*?)?\]{2}([^\]])/g, '$1<a class="autolink" href="/wiki/$2">[[$2$3]]</a>$4'); // Make wikilink code into links
    content = content.replace(/([^\{])\{{2}(subst\:|msg\:)?([^\{\}\|\<\>\n]*)([^\{\}\<\>\n]*?)?\}{2}([^\}])/g, '$1<a class="autolink" href="/wiki/Template:$3">{{$2$3$4}}</a>$5'); // Make template code into links
    targetdiv.innerHTML = content; // Write it back
});

// </pre>