在Greasemonkey脚本中,如何通过其元素定位页面?

时间:2014-02-07 23:17:12

标签: greasemonkey userscripts tampermonkey

我想使用Greasemonkey脚本更改页面,但该页面是CGI POST调用的结果,因此URL如下所示:

http://www.example.com/cgi-bin/foo.pl

显然我不能在Greasemonkey脚本中使用@include,因为该URL适合应用程序可以生成的很多页面。

在执行操作之前,我可以在脚本中查找页面上的一些元素:

if (document.getElementById('someIdentifier')) {
  // do changes in here
}

但我想知道是否有更好的,可能内置的方法来做到这一点。

1 个答案:

答案 0 :(得分:1)

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);