Search code examples
javascriptgreasemonkeytampermonkey

Userscript to restore normal link click behavior to open in a new tab when ctrl+clicked


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.


Solution

  • 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);