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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11195658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:21:41  来源:igfitidea点击:

Run Greasemonkey script on the same page, multiple times?

javascriptajaxgreasemonkeytampermonkey

提问by Firefox

I'm totally new to Greasemonkey, javascript, in fact all the UI stuff.

我完全不熟悉 Greasemonkey、javascript,实际上是所有 UI 的东西。

Requirement: Userscript is run by GS once after the page loads. However, I need the same script to be run multiple times without refresh

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

Use case: For ex, Amazon.com search happens using Ajax. I need to embed a custom element in the search results.

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

I need to inject my content to the search-results-div along with the results every time a search happens in the same page (there's no page refresh)

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

My current script runs only with the page refresh.

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

I hope above explanation is clear. Please help.

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

回答by Brock Adams

The simplest, most robust way is to use the waitForKeyElements() utility.

最简单、最可靠的方法是使用waitForKeyElements() 实用程序

Here is a complete scriptthat uses jQuery and waitForKeyElementsto alter Amazon search results:

这是一个使用 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);

回答by ncreep

You can use the DOMNodeInsertedevent to call your callback, e.g.:

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

document.addEventListener('DOMNodeInserted', function() { alert('hi') }, false);

Note that the event will be triggered by any change in the page structure, so you'll have to check that you're targeting the right change.

请注意,页面结构中的任何更改都会触发该事件,因此您必须检查您的目标更改是否正确。