views:

928

answers:

2

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...
A: 

Have you tried:

(function() {
    var yourFunction = function() 
    {
       // ...
    }
    window.addEventListener("load", yourFunction, false);
})();
Assaf Lavie
Good thought. But, the listener still seems to start only after the <html> tag. Thanks though.
anschauung
greasemonkey executes the userscript on the domready event, the load event is fired at the later point after all the resources have been loaded
ionelmc
+1  A: 

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.

porneL