了解Greasemonkey如何运行用户脚本 [英] Understanding how Greasemonkey runs user scripts

查看:176
本文介绍了了解Greasemonkey如何运行用户脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Greasemonkey,希望可以对网页进行一些改进.

I'm learning Greasemonkey with the hopes of making some improvements to a webpage.

我认为我对JavaScript有很好的了解,但是我不理解在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脚本仅在该JS完成后才能运行.

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.

假设这是我正在尝试使用Greasemonkey修改的文档

Let's say this is the document that I'm trying to modify with Greasemonkey

<html>
 <script>
   //insert a button with id="mybutton"
 </script>
</html>

我希望在运行Greasemonkey脚本之前完成<script>代码,因为我想更改其背景颜色.

I want the <script> code to complete before my Greasemonkey script is run, because I want to alter its background color.

推荐答案

Greasemonkey 在DOMContentLoaded事件上运行默认情况下.这意味着,除了可能大图像和某些javascript(在load事件上触发的脚本或AJAX-in内容)添加的内容外,所有内容都将在页面中.

Greasemonkey runs at the DOMContentLoaded event by default. 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).

如果您要等到大介质加载完毕并运行"onload"脚本后,请使用:

If you want to wait until even large media has loaded and "onload" scripts have run, use:

window.addEventListener ("load", Greasemonkey_main, false);

function Greasemonkey_main () {

    //***** PUT YOUR GREASEMONKEY CODE HERE.
}

请勿使用 unsafeWindow.onload = function(){ ... }window.onload = function() { /* logic here */ },如其他建议一样. 这些不仅是不好的做法,而且也不适用GM ,但是unsafeWindow在这种情况下是不必要的安全风险.

Do not use unsafeWindow.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.

由于您指示您关心的节点是由javascript添加的,因此等待load事件通常不起作用. 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.

在这种情况下,最好的方法是轮询您感兴趣的元素("#mybutton").请参阅对"AJAX请求上的Fire Greasemonkey脚本"的答案.

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".

这篇关于了解Greasemonkey如何运行用户脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆