Open-link-in-new-tab

Append "[[New tab]]" to links that don't open in new tab. Skip image links.

  1. // ==UserScript==
  2. // @name Open-link-in-new-tab
  3. // @namespace cyyyu
  4. // @version 0.1
  5. // @description Append "[[New tab]]" to links that don't open in new tab. Skip image links.
  6. // @author Chuang Yu
  7. // @match *://*/*
  8. // @icon https://www.google.com/s2/favicons?sz=64&domain=sourceforge.net
  9. // @grant none
  10. // @run-at document-end
  11. // @license MIT
  12. // ==/UserScript==
  13.  
  14. (function() {
  15. 'use strict';
  16.  
  17. const aTags = document.querySelectorAll('a');
  18. const linksOpenInWindow = Array.from(aTags).filter(a => {
  19. const isInWindow = a.getAttribute('target') !== '_blank';
  20. if (!isInWindow) return false;
  21. const url = a.getAttribute('href');
  22. if (!url || !url.startsWith('http')) return false;
  23. const hasImage = a.querySelector('img') || a.querySelector('svg');
  24. if (hasImage) return false;
  25. return true;
  26. });
  27. linksOpenInWindow.forEach(a => {
  28. const newLink = document.createElement('a');
  29. newLink.setAttribute('href', a.getAttribute('href'));
  30. newLink.setAttribute('target', '_blank');
  31. newLink.textContent = ' [[New tab]]';
  32. a.appendChild(newLink);
  33. });
  34. })();