多次在同一页面上运行Greasemonkey脚本?

Fir*_*fox 31 javascript ajax greasemonkey tampermonkey

我是Greasemonkey,javascript的新手,实际上是所有UI的东西.

要求:用户脚本在页面加载后由GS运行一次.但是,我需要在不刷新的情况下多次运行相同的脚本

使用案例:例如,使用Ajax进行Amazon.com搜索.我需要在搜索结果中嵌入自定义元素.

每次在同一页面中进行搜索时,我都需要将我的内容注入search-results-div以及结果(没有页面刷新)

我当前的脚本仅在页面刷新时运行.

我希望上面的解释清楚.请帮忙.

Bro*_*ams 47

最简单,最健壮的方法是使用waitForKeyElements()实用程序.

这是一个使用jQuery并改变亚马逊搜索结果的完整脚本waitForKeyElements:

// ==UserScript==
// @name     _Amazon Search, alter results
// @include  http://www.amazon.com/s/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.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 addCustomSearchResult (jNode) {
    //***** YOUR CODE HERE *****
    jNode.prepend (
        '<div id="result_000" class="fstRow">Buy my stuff, instead!</div>'
    );
}

waitForKeyElements ("#atfResults", addCustomSearchResult);
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢!!!!!虽然我有一些编程经验,但这个UI脚本有点麻烦(烦人)我.您的代码完全按照我想要的方式执行.我会定制它以满足进一步的要求.再次感谢. (2认同)

ncr*_*eep 6

您可以使用该DOMNodeInserted事件来调用您的回调,例如:

document.addEventListener('DOMNodeInserted', function() { alert('hi') }, false);
Run Code Online (Sandbox Code Playgroud)

请注意,该事件将由页面结构中的任何更改触发,因此您必须检查是否定位了正确的更改.