how to run greasemonkey script before the page content is displayed?

前端 未结 3 684
别跟我提以往
别跟我提以往 2020-12-13 14:24

I am writing a plug-in for Firefox and using greasemonkey script to do that (I compile the user script using this tool http://arantius.com/misc/greasemonkey/script-compiler)

3条回答
  •  一向
    一向 (楼主)
    2020-12-13 15:00

    Using the @run-at document-start as suggested in the answer by @kwah my script executed before the content I wanted to manipulate was in the document body. As a work-around I set up an interval running my script 5 times/second until document.readyState == "complete" (or until 20 seconds have passed).

    This worked well for my case:

    // ==UserScript==
    // ...
    // @run-at      document-start
    // ==/UserScript==
    
    var greasemonkeyInterval = setInterval(greasemonkey, 200);
    var greasemonkeyStart = (new Date()).getTime();
    
    function greasemonkey() {
    
        // ...
    
        // waiting for readyState (or timeout)
        if (
            (new Date()).getTime() - greasemonkeyStart > 20000
            || document.readyState == "complete"
        ) {
            clearInterval(greasemonkeyInterval);
        }
    
    };
    

    If you're more sure about that the content will be there at documentready I think something like this would be more preferable:

    function greasemonkey() {
    
        if (
            document.readyState != "interactive"
            && document.readyState != "complete"
        ) {
            return;
        }
    
        // ...
    
        clearInterval(greasemonkeyInterval);
    
    }
    

提交回复
热议问题