Javascript 突出显示文本的Userscript在控制台中工作,但不起作用
我正试图找到一种方法,让下面的代码在页面加载时(或者我猜是在页面加载之后)加载,并自动突出显示页面上的某些单词或短语。现在,除非我将代码插入控制台,否则代码不会启动。我一直在测试的代码受过去线程()的影响很大,如下所示:Javascript 突出显示文本的Userscript在控制台中工作,但不起作用,javascript,google-chrome,highlight,userscripts,tampermonkey,Javascript,Google Chrome,Highlight,Userscripts,Tampermonkey,我正试图找到一种方法,让下面的代码在页面加载时(或者我猜是在页面加载之后)加载,并自动突出显示页面上的某些单词或短语。现在,除非我将代码插入控制台,否则代码不会启动。我一直在测试的代码受过去线程()的影响很大,如下所示: // ==UserScript== // @name Highlight Text // @description Highlights text within HTML // @require https://ajax.googleapis.com/ajax/
// ==UserScript==
// @name Highlight Text
// @description Highlights text within HTML
// @require https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// @grant GM.getValue
// ==/UserScript==
function highlightWord(word) {
var xpath = "//text()[contains(., '" + word + "')]";
var texts = document.evaluate(xpath, document.body, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (n = 0; n < texts.snapshotLength; n++) {
var textNode = texts.snapshotItem(n);
var p = textNode.parentNode;
var a = [];
var frag = document.createDocumentFragment();
textNode.nodeValue.split(word).forEach(function(text, i) {
var node;
if (i) {
node = document.createElement('span');
node.style.backgroundColor = 'lightgreen';
node.appendChild(document.createTextNode(word));
frag.appendChild(node);
}
if (text.length) {
frag.appendChild(document.createTextNode(text));
}
return a;
});
p.replaceChild(frag, textNode);
}
}
highlightWord('sample');
/==UserScript==
//@name高亮显示文本
//@description突出显示HTML中的文本
//@需要https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
//@需要https://gist.github.com/raw/2625891/waitForKeyElements.js
//@grant GM_addStyle
//@grant GM.getValue
//==/UserScript==
函数highlightWord(word){
var xpath=“//text()[包含(,““+word+”)];
var text=document.evaluate(xpath,document.body,null,XPathResult.UNORDERED\u NODE\u SNAPSHOT\u TYPE,null);
对于(n=0;n
例如,我想突出显示下一页中的“示例”一词:
我无法获得在页面加载时自动突出显示文本的代码。我做了一些研究,我认为这个页面可能会受到AJAX的影响,因此拨款是最高的。现在,页面加载时什么也没有发生,但是当我手动将代码插入页面控制台时,它工作正常,指定的文本确实会突出显示。这似乎是一个非常简单的解决办法,但我显然在掩饰一些东西。提前谢谢 我没有意识到highlightword是区分大小写的,我还为我想要的特定站点使用了@include,现在它工作得很好。我没有运行tampermonkey进行测试,但是可以尝试绑定到window
load
事件,而不是立即调用函数(window.addEventListener(“load”),()=>highlightWord('sample');
)?或者仅仅设置一个超时就可以了(window.setTimeout(()=>highlightWord('sample'),1000);
)我认为您应该在脚本中的@include
或@match
标记中包含站点地址。否则它将无法运行。为什么不在创建新脚本时使用Tampermonkey提供的模板呢?因此在采纳了您的建议后,我解决了问题。我没有意识到highlightword是区分大小写的,我还为我想要的特定站点使用了@include。谢谢你的回复!你应该对此发表评论,或者编辑你自己的问题帖子。