使用Greasemonkey或Tamper猴子,如何在Dictionary.com打开Thesaurus.com (反之亦然)时查看当前的以红色标出的链接被单击。定义。
我看到我可以使用window.location.pathname检索“/浏览/测试”或搜索的任何单词,然后我可以将它们放在相反链接的主机名上。
Thesaurus.com链接的HTML:<a href="http://www.thesaurus.com/" data-linkid="qxnxzj">Thesaurus.com</a>
Dictionary.com链接的HTML:<a href="http://www.dictionary.com/" data-linkid="tqks0v">Dictionary.com</a>
所以我要用document.querySelectorAll("a[href='http://www.thesaurus.com']");或document.querySelectorAll('[data-linkid=qxnxzj]');来选择它
我担心的是后一种选择方法,以防数据链接被公司的web开发人员更改。
然而,最终,我仍然不知道如何实现这一点。我是在监听document上的所有点击,还是仅仅在<a>标签上,等等?做这件事最有效的方法是什么?
此外,如何在ctrl+clicked时在新选项卡中打开这些链接,或者在shift+clicked时打开新窗口?目前,它在同一个浏览器选项卡中打开ctrl+clicked和shift+clicked链接。
发布于 2017-03-07 21:34:10
以下代码能够充分实现我问题中概述的所有目标:
// ==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);
})();https://stackoverflow.com/questions/42637715
复制相似问题