Open links in current tab

Open links in current tab regardless of _target or site's preferences. Ctrl-click: background tab, Ctrl-Shift-click: foreground tab, Shift-click: new window, Alt-click: force open in current tab

目前为 2016-09-22 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Open links in current tab
  3. // @author wOxxOm
  4. // @description Open links in current tab regardless of _target or site's preferences. Ctrl-click: background tab, Ctrl-Shift-click: foreground tab, Shift-click: new window, Alt-click: force open in current tab
  5. // @namespace http://target._blank.is.retarded
  6. // @version 2.1.1
  7. // @include *
  8. // @run-at document-start
  9. // @grant GM_openInTab
  10. // ==/UserScript==
  11.  
  12. var suppressing;
  13. window.addEventListener('mouseup', function(e) {
  14. if (e.button > 1)
  15. return;
  16. var link = e.target.closest('a');
  17. if (!link || (link.getAttribute('href') || '').match(/^(javascript|#|$)/))
  18. return;
  19. var b = e.button, c = e.ctrlKey, a = e.altKey, s = e.shiftKey, m = e.metaKey;
  20. if (!a && link.target != '_blank') {
  21. var observer = new MutationObserver(function(mutations) {
  22. if (link.target == '_blank') {
  23. link.removeAttribute('target');
  24. console.log('[Open links in current tab] prevented dynamic target=_blank for', link.href);
  25. }
  26. });
  27. observer.observe(link, {attributes:true, attributeFilter:['target'], characterData:true});
  28.  
  29. var _open = unsafeWindow.open;
  30. var timeout = setTimeout(function() {
  31. unsafeWindow.open = _open;
  32. observer.disconnect();
  33. }, 50);
  34. unsafeWindow.open = exportFunction(function(url, name, features) {
  35. if (!features) {
  36. console.log('[Open links in current tab] prevented window.open for', url);
  37. location.href = link.href;
  38. } else
  39. _open(url, name, features);
  40. unsafeWindow.open = _open;
  41. clearTimeout(timeout);
  42. }, unsafeWindow);
  43. return;
  44. }
  45. if (!b && !c && !s && !m && (link.href.replace(/#.*/, '') != location.href.replace(/#.*/, '') || a))
  46. location.href = link.href;
  47. else if (b == 1 || c && !a && !m)
  48. GM_openInTab(link.href, !s);
  49. else if (window.chrome && !b && s && !c && !a && !m)
  50. link.cloneNode().dispatchEvent(new MouseEvent('click', {shiftKey: true}));
  51. else
  52. return;
  53. suppressing = true;
  54. prevent(e);
  55. }, true);
  56.  
  57. window.addEventListener('click', prevent, true);
  58. window.addEventListener('auxclick', prevent, true);
  59.  
  60. function prevent(e) {
  61. if (!suppressing)
  62. return;
  63. e.preventDefault();
  64. e.stopPropagation();
  65. e.stopImmediatePropagation();
  66. setTimeout(function() {
  67. suppressing = false;
  68. }, 50);
  69. }