【发布时间】:2019-01-05 02:58:17
【问题描述】:
我正在尝试找出一种方法来在页面加载时(或者我猜是之后)加载以下代码,并自动突出显示页面上的某些单词或短语。现在,除非我将代码插入控制台,否则代码不会启动。我一直在测试的代码受过去线程 (Greasemonkey: Highlight many words in a HTML-File) 的影响很大,如下所列:
// ==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');
例如,我想突出显示以下页面中的“样本”一词:https://www.snapsurveys.com/survey-software/sample-surveys/
我无法获取代码以在页面加载时自动突出显示文本。我做了一些研究,我认为该页面可能受 AJAX 影响,因此顶部的赠款。现在,在页面加载时没有任何反应,但是当我手动将代码插入页面的控制台时,它工作正常并且指定的文本确实被突出显示。这似乎是一个非常简单的修复,但我显然在掩饰一些东西。提前致谢!
【问题讨论】:
-
我没有运行 tampermonkey 来测试,但也许尝试绑定到窗口
load事件而不是立即调用函数 (window.addEventListener("load", () => highlightWord('sample'));)?或者可能只是设置一个超时就可以了 (window.setTimeout(() => highlightWord('sample'), 1000);) -
我认为您应该在脚本中的
@include或@match标记中包含站点地址。否则它不会运行。 -
创建新脚本时为什么不使用 Tampermonkey 提供的模板?
-
所以在听取了您的建议后,我发现了问题所在。我没有意识到 highlightword 是区分大小写的,我还为我想要的特定网站使用了 @include。感谢您的回复!
标签: javascript google-chrome highlight userscripts tampermonkey