Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make my userscript wait for other scripts to load

[Edit: I'm replacing the original, confusing question with a simplified example demonstrating the problem.]

Background

I'm trying to write a userscript which will run in Chrome. This script needs to call a JavaScript function AlertMe() that is outside of the userscript -- this function is part of the page and contains variables that are generated dynamically on the server-side, so it isn't possible to re-write this function in my userscript.

Code

Script on the page (visit the page):

<script type="text/javascript">
    function AlertMe()
    {
        alert("Function AlertMe was called!");
        // then do stuff with strings that were dynamically generated
        // on the server so that I can't easily rewrite this into the userscript
    }
</script>

My userscript (install it in Chrome):

function tryAlert()
{
    if (typeof AlertMe == "undefined") {
        console.log('AlertMe is undefined.');
        window.setTimeout(tryAlert, 100);
    }
    else {
        AlertMe();
    }
}

tryAlert();

The Problem

When I tried to simply call the function, Chrome's console let me know that AlertMe is not defined. Thinking that this was because my userscript was running before all other scripts had been loaded, I used setTimeout to wait for the AlertMe function to become defined.

Unfortunately, if you install the script then visit the page, you'll see that this just outputs AlertMe is undefined. forever and never calls the function. If you type typeof AlertMe into Chrome's console, it will correctly respond with "function", so why is it that my userscript always thinks that AlertMe is undefined?

like image 501
Michael Martin-Smucker Avatar asked Feb 23 '11 15:02

Michael Martin-Smucker


1 Answers

You can always write a little function that checks to see if the function is loaded

function waitForFnc(){
  if(typeof absearch == "undefined"){
    window.setTimeout(waitForFnc,50);
  }
  else{
    runMyFunction();
  }
}

function runMyFunction(){
    var urlParams = window.location.search.substring(1).split('&'),
        username = "",
        hscEmailInput = document.getElementById('userfield6'),
        i = 0;
    if (urlParams !== "") {
        for (i = 0; i < urlParams.length; i++) {
            if (urlParams[i].substr(0,4) === "USER") {
                username = urlParams[i].replace('USER=', '');
                hscEmailInput.value = username + '@example.com';
                absearch('&PAGESIZE=1');
            }
        }
    }
}

waitForFnc();
like image 91
epascarello Avatar answered Sep 19 '22 18:09

epascarello