How does one have Greasemonkey run before *anything* else in the page?

烂漫一生 提交于 2019-12-07 07:09:34

问题


Is it possible to have Greasemonkey scripts run before anything else on the page?

I'm aware of @run-at document-start, but this appears to run immediately after the <HTML> tag. Normally this isn't a problem, but if the page is misformatted as in the example below, there doesn't seem to be anything I can do.

I'd appreciate any suggestions or ideas. Thanks!

<script>alert('This is an annoying message.');</script>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
        <HEAD>
...etc...

回答1:


It's not possible, because HTML requres that scripts are executed during parsing or not at all, e.g. this is allowed:

<script> document.write('<!'+'--'); </script>

If browser goes past this script without executing it, it will see completely different document, therefore you can't analyze DOM of HTML document before scripts run.

Opera solves this problem in UserJS by firing BeforeScript events, allowing UserJS to change/remove scripts at the very last moment.




回答2:


Actually, @run-at document-start does pretty much run the GM script before anything from the page.

In your case, the following code will work in conjunction with @run-at document-start:

_oldAlert           = alert;
unsafeWindow.alert  = function () {};

/*-- Optionally, wait for the DOM, then set an onload handler to restore
    alert().
*/



回答3:


Have you tried:

(function() {
    var yourFunction = function() 
    {
       // ...
    }
    window.addEventListener("load", yourFunction, false);
})();


来源:https://stackoverflow.com/questions/708136/how-does-one-have-greasemonkey-run-before-anything-else-in-the-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!