Using Greasemonkey or Tampermonkey, how can I have the currently viewed definition at Dictionary.com open at Thesaurus.com (and vice versa) when the links circled in red are clicked.
I see that I can use window.location.pathname
to retrieve "/browse/test" or whatever word is being searched, which I can then put on the opposite link's hostname.
The HTML of the Thesaurus.com link: <a href="http://www.thesaurus.com/" data-linkid="qxnxzj">Thesaurus.com</a>
The HTML of the Dictionary.com link: <a href="http://www.dictionary.com/" data-linkid="tqks0v">Dictionary.com</a>
So I was going to either select it with document.querySelectorAll("a[href='http://www.thesaurus.com']");
or document.querySelectorAll('[data-linkid=qxnxzj]');
I was concerned about the latter method of selection, just in case the data-linked was changed by the company's web developer.
However, ultimately, I am still uncertain of how to implement this. Do I listen for all clicks on the document
, or just on <a>
tags, etc.? What is the most efficient way to do this?
Furthermore, how can I have these links open in a new tab when ctrl+clicked, or a new window when shift+clicked? Currently, it opens ctrl+clicked and shift+clicked links in the same browser tab.
The follow code was able to fully achieve all goals outlined in my question:
// ==UserScript==
// @name Restore links behavior at Thesaurus.com
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match *://www.thesaurus.com/*
// @match *://www.dictionary.com/*
// @run-at document-end
// @grant none
// ==/UserScript==
(function() {
'use strict';
document.querySelectorAll('[data-linkid]').forEach(el => el.removeAttribute('data-linkid'));
document.addEventListener('click', function(e) {
var link = e.target.closest('a');
//var link = e.target.closest('#content a'); // limit to the #content area
var path = window.location.pathname; // /browse/myword
if (link && link.getAttribute('href') != '#') {
e.stopPropagation();
}
if (link && link.getAttribute('href') == 'http://www.thesaurus.com/') {
link.setAttribute('href', 'http://www.thesaurus.com' + path);
}
else if (link && link.getAttribute('href') == 'http://www.dictionary.com/') {
link.setAttribute('href', 'http://www.dictionary.com' + path);
}
}, true);
})();