【发布时间】:2012-02-06 02:23:33
【问题描述】:
我确实在 google 和 userscripts 网站上做了一些研究,但没有找到答案。
所以基本上我如何检查页面上是否找到特定文本? 并且文本没有特殊的标签或任何东西。
【问题讨论】:
标签: text greasemonkey
我确实在 google 和 userscripts 网站上做了一些研究,但没有找到答案。
所以基本上我如何检查页面上是否找到特定文本? 并且文本没有特殊的标签或任何东西。
【问题讨论】:
标签: text greasemonkey
对于 FF GM 来说是一种粗略但快速的方法:
if (/Text you are looking for/i.test (document.body.innerHTML) )
{
alert ("Found it!");
}
//--- Looking for one of two different texts...
if (/(Text ONE that you are looking for)|(Text TWO that you are looking for)/i.test (document.body.innerHTML) )
{
alert ("Found one!");
}
对于更集中的搜索,请使用jQuery contains,如this previous question。
【讨论】:
innerHTML 适用于 Chrome,因此代码应该可以工作。我之所以提到它,是因为有些人对innerHTML 产生了兴趣,因为在IE 上写入 是有问题的。无论如何,我们只是在扫描它。
"Also what would i do if i wanted to search for more than 1 different thing?" --- 更新了答案以显示该概念。
例如,如果在此页面上找到文本 specific text,此脚本将显示。
// ==UserScript==
// @name so5059986
// @namespace test
// @description test
// @include http://stackoverflow.com/questions/5059986/how-to-have-greasemonkey-check-if-text-if-found-on-page
// ==/UserScript==
var xpathResult = document.evaluate("(//text()[contains(., 'specific text')])[1]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
var node=xpathResult.singleNodeValue;
if (node==null)
alert("text not found");
else
alert("text found on page");
我不知道你所说的特殊标签是什么意思。文本总是在一些标签内。
【讨论】:
if (node == null) {}; 存在语法错误,并且 jsFiddle 选项对于此类代码不正确。将{}; 替换为noop; 或直接转至jsfiddle.net/tQFLz/4——但要准备好每3 秒生气一次。 ;)