Jump to content

User:Splarka/encodeeverything.js

From Wikipedia, the free encyclopedia
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
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.
/* Over-Encode URLs, version [0.0.1]
Originally from: http://en.wikipedia.org/wiki/User:Splarka/encodeeverything.js

safe to encode,  everything but:
  mw.config.get('wgServer') + mw.config.get('wgArticlePath')
  wgServer
  * + wgArticlePath
  %2F /  %5C \  %3F ?  
  %3D =  %26 &  %2B +
*/

addOnloadHook(function() {
  if(window.encodeStuffAllLinksAuto) {
    encodeStuffAllLinks();
    return;
  }
  mw.util.addPortletLink('p-tb','javascript:encodeStuffAllLinks();','Encode links','t-encode','Encode the hell out of all links on this page, yeah!');
});

function encodeStuffAllLinks() {
  var a = document.getElementsByTagName('a');
  for(var i=0;i<a.length;i++) {
    href = a[i].getAttribute('href',2)
    if(!href) continue
    var ap = wgArticlePath.replace(/\$1$/ig,'');
    var sp = wgScriptPath + '/';
    if(href.indexOf(ap) != -1) {
      //contains '/wiki/'
      var nhref = href.substring(0,href.indexOf(ap) + ap.length) + encodeStuff(href.substring(href.indexOf(ap) + ap.length));
      a[i].setAttribute('href',nhref);
    } else if(href.indexOf(sp) == 0) {
      //starts with '/w/'
      var nhref = encodeStuff(href);
      a[i].setAttribute('href',nhref);
    } else if(href.indexOf(wgServer) == 0) {
      //elsewise starts with the current server name
      var nhref = href.substring(0,wgServer.length) + encodeStuff(href.substring(wgServer.length));
      a[i].setAttribute('href',nhref);
    }
  }
}

function encodeStuff(stuff) {
  var code = '';
  var txt = decodeURIComponent(stuff);
  for(var i=0;i<txt.length;i++) {
    if(/^[\\\/?=&+]$/.test(txt[i])) {
      code += txt[i];
   } else if(txt.charCodeAt(i) > 127 ) {
      code += encodeURIComponent(txt[i]);
   } else {
      code += '%' + txt.charCodeAt(i).toString(16);
    }
  }
  return code;
}