// ==UserScript==
// @name            change _blank target
// @namespace       http://www.fpm-edv.at/userscripts/
// @description     Changes the target of links which open new windows
// @include         *
// ==/UserScript==

(function() {
   // very heavy to do this like this but haven't found an other solution
   document.addEventListener('click', function(event) {
      // it must be a left click!
      if (event.which != 1) {
         return;
      }
      // get the target node of the click
      var node = event.target;
      // this is necessary because in the <a> tag can be other Tags
      // Stop if <a> tag found
      while(node.nodeName.toLowerCase() != 'a') {
         // if <body> tag or there is an onclick attribute stop
         if (node.nodeName.toLowerCase() == 'body' || node.getAttribute('onclick') != null || node.getAttribute('onClick') != null) {
            return;
         }
         // go down the spine
         node = node.parentNode;
      }

      // found a tag does it have a href attribute and no aonclick attribute
      if(node.getAttribute('href') != null && node.getAttribute('onclick') == null && node.getAttribute('onClick') == null) {
         // check if target, _base_target is not _new or _blank
         if (node.getAttribute('target') != "_blank" && node.getAttribute('target') != "_new" && node.getAttribute('_base_target') != "_blank" && node.getAttribute('_base_target') != "_new") {
            return;
         }
         // prefent default behavior
         event.preventDefault();
         event.stopPropagation();
         // do the click so overwrite the standard click behavior
         window.location.href = node.getAttribute('href');
      }
   }, true);
})();

