简体   繁体   English

了解Greasemonkey如何运行用户脚本

[英]Understanding how Greasemonkey runs user scripts

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. 例如,如果文档中本身存在JavaScript,则会向页面插入一些元素。 I want my Greasemonkey script to run only after that JS completes. 我希望我的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. 我想在运行Greasemonkey脚本之前完成<script>代码,因为我想改变它的背景颜色。

Greasemonkey runs at the DOMContentLoaded event by default. 默认情况下,Greasemonkey 在DOMContentLoaded事件中运行 This means that everything will be in the page except for possibly large images and stuff added by some javascripts (scripts that fire on the load event or that AJAX-in content). 这意味着一切都将在页面中,除了可能是大型图像和一些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 use unsafeWindow.onload = function(){ ... } or window.onload = function() { /* logic here */ } as others have suggested. 不要像其他人建议的那样使用 unsafeWindow.onload = function(){ ... }window.onload = function() { /* logic here */ } These are not only poor practice/won't work in GM , but the unsafeWindow is an unnecessary security risk in this case. 这些不仅是糟糕的做法/不会在通用汽车公司工作 ,但在这种情况下, 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. 由于您表示您关注的节点是通过javascript添加的,因此等待load事件通常不起作用。 JS can add, remove or edit nodes at any time. JS可以随时添加,删除或编辑节点。

The best approach in cases like these is to poll for the element you are interested in ( "#mybutton" ). 在这种情况下,最好的方法是轮询你感兴趣的元素( "#mybutton" )。 See this answer to "Fire Greasemonkey script on AJAX request" . 请参阅“关于AJAX请求的Fire Greasemonkey脚本”的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM