0

Using Greasemonkey or Tampermonkey, how can I have listed synonyms (which are links) at thesaurus.com open in a new tab when Ctrl+clicked, or a new window when Shift+clicked? Currently, it opens Ctrl+clicked and Strl+clicked links in the same tab.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
J D
  • 113
  • 3

1 Answers1

1

The site breaks the standard link behavior, which is a very bad thing to do, by attaching its own primitive click handlers that don't support modifier keys.

Sometimes you can use jQuery('a').off('click') but a universal approach is:

  1. Attach a click listener on window, the topmost DOM object, before the site attaches its own listeners: use @run-at document-start metadata key.
  2. Specify true for the useCapture parameter of addEventListener to intercept the event at the very start of the capturing phase from window to the click target. Thus we additionally increase the chances of interception before it bubbles to the element on which the site listens for click events (could be anything, from stuff inside a to window) with a standard non-capturing listener.
  3. Use event.stopPropagation() to prevent the subsequently attached site listeners from seeing the click event.
  4. Protect legitimate link-based site functionality by skipping dummy links with self-redirects via # in target link href and/or by limiting the CSS selector of the click target to the content area.

// ==UserScript==
// @name    Restore links behavior
// @match   *://www.thesaurus.com/*
// @run-at  document-start
// ==/UserScript==

window.addEventListener('click', function(e) {
    var link = e.target.closest('a');
    //var link = e.target.closest('#content a'); // limit to the #content area
    if (link && link.getAttribute('href') != '#') {
        e.stopPropagation();
    }
}, true);
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • Good, but this will also break desired menus and buttons. You should scope the links to reduce side effects. Something like `if(e.target.closest('.synonyms a'))`, for example. (Specific to that site) – Brock Adams Mar 06 '17 at 21:45
  • 1
    Indeed. In this case even `#content a` might work but with the `#`-checking it's not needed apparently. – wOxxOm Mar 06 '17 at 21:56
  • @wOxxOm, that's awesome, thank you. Are there any side-effects I can expect from this? – J D Mar 06 '17 at 22:27
  • Well, you can become addicted to this userscript and allow it to run on more sites... – wOxxOm Mar 06 '17 at 22:33
  • Thank you @wOxxOm, your solution works like a charm. I actually have a follow-up question, if you'd be so kind: http://stackoverflow.com/questions/42637715/using-grease-tampermonkey-how-can-i-have-the-currently-viewed-definition-at-dic – J D Mar 06 '17 at 23:49
  • 1
    That new question doesn't seem to have a potential to be generally useful like this one, for which I already had an existing solution, so personally I'm not interested. – wOxxOm Mar 06 '17 at 23:55