javascript 了解 Greasemonkey 如何运行用户脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8772137/
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
Understanding how Greasemonkey runs user scripts
提问by Mike
I'm learning Greasemonkey with the hopes of making some improvements to a webpage.
我正在学习 Greasemonkey,希望对网页进行一些改进。
I think I have a good grasp of JavaScript, but I don't understand at what point in the rendering of the document the Greasemonkey user script is executed.
我认为我对 JavaScript 有很好的掌握,但我不明白 Greasemonkey 用户脚本在文档呈现的哪个点被执行。
For instance, what if there is JavaScript natively inside the document that inserts some elements to the page. I want my Greasemonkey script to run only after that JS completes.
例如,如果文档中原生有 JavaScript 将一些元素插入页面会怎样。我希望我的 Greasemonkey 脚本仅在 JS 完成后运行。
Let's say this is the document that I'm trying to modify with Greasemonkey
假设这是我尝试使用 Greasemonkey 修改的文档
<html>
<script>
//insert a button with id="mybutton"
</script>
</html>
I want the <script>
code to complete before my Greasemonkey script is run, because I want to alter its background color.
我希望<script>
代码在运行 Greasemonkey 脚本之前完成,因为我想更改其背景颜色。
回答by Brock Adams
Greasemonkey runs at the DOMContentLoaded eventby default. This means that everything will be in the page except for possiblylarge images and stuff added by some javascripts (scripts that fire on the load
event or that AJAX-in content).
默认情况下,Greasemonkey在 DOMContentLoaded 事件中运行。这意味着除了可能的大图像和一些 javascripts(触发load
事件的脚本或 AJAX-in 内容的脚本)添加的内容之外,所有内容都将在页面中。
If you want to wait until even large media has loaded and "onload" scripts have run, use:
如果您想等到大型媒体已加载并且“onload”脚本已运行,请使用:
window.addEventListener ("load", Greasemonkey_main, false);
function Greasemonkey_main () {
//***** PUT YOUR GREASEMONKEY CODE HERE.
}
Do not useunsafeWindow.onload = function(){ ... }
or window.onload = function() { /* logic here */ }
as others have suggested. These are not only poor practice/won't work in GM, but the unsafeWindow
is an unnecessary security risk in this case.
不要使用unsafeWindow.onload = function(){ ... }
或window.onload = function() { /* logic here */ }
按照其他人的建议使用。 这些不仅是糟糕的做法/在 GM 中不起作用,而且unsafeWindow
在这种情况下是不必要的安全风险。
However, dealing with JS-added content:
但是,处理 JS 添加的内容:
Since you indicated that the node you care about is added by javascript, waiting for the load
event will often not work. JS can add, remove or edit nodes at any time.
由于您指出您关心的节点是由 javascript 添加的,因此等待load
事件通常不起作用。JS 可以随时添加、删除或编辑节点。
The best approach in cases like these is to poll for the element you are interested in ("#mybutton"
). See this answer to "Fire Greasemonkey script on AJAX request".
在这种情况下,最好的方法是轮询您感兴趣的元素 ( "#mybutton"
)。请参阅“针对 AJAX 请求的 Fire Greasemonkey 脚本”的答案。