我想使用 Greasemonkey 脚本更改页面,但该页面是 CGI POST 调用的结果,因此 URL 如下所示:
http://www.example.com/cgi-bin/foo.pl
很明显,我不能在 Greasemonkey 脚本中使用 @include
,因为该 URL 适合应用程序可以生成的许多页面。
在执行操作之前,我可以在脚本中查找页面上的一些元素:
if (document.getElementById('someIdentifier')) {
// do changes in here
}
但我想知道是否有更好的、也许是内置的方法来做到这一点。
最佳答案
Greasemonkey(以及大多数用户脚本引擎)没有内置方法来通过元素定位页面。您的脚本需要轮询或使用类似 Mutation Observers 的机制检查所需的元素。
执行此操作的一个简便方法是使用 the waitForKeyElements() utility ,并且您仍然希望使用 @include
、@exclude
和/或 @match
指令来缩小页面触发范围有可能。
这是一个完整的 Greasemonkey/Tampermonkey 脚本,说明了该过程:
// ==UserScript==
// @name _Do something after select posts
// @include http://www.example.com/cgi-bin/foo.pl*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
function processTargetElement (jNode) {
//***** YOUR CODE HERE *****
jNode.css ("background", "pink");
}
waitForKeyElements ("#someIdentifier", processTargetElement);
关于greasemonkey - 在 Greasemonkey 脚本中,如何通过元素定位页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21639516/