Paul Calabro
Paul Calabro

Reputation: 1906

onload Functions Firing Out Of Order

Any idea why the following code:

    <script>        
        var access_token;
        var access_token_secret;        

        function Login(){
            img = document.getElementById('authenticate');
            img.src = 'authenticate.png';
            login = document.getElementById('login');
            login.style.visibility="visible";
        }
        function cookieHandlerStep1(){
            chrome.cookies.get({ 
                url:URL_GOES_HERE, 
                name:'access_token'
            },
            function(cookie){
                if(cookie){ 
                    access_token = cookie['value'];
                    cookieHandlerStep2();
                } else{ 
                    Login();
                }
            });
        }
        function cookieHandlerStep2(){
            chrome.cookies.get({ 
                url:URL_GOES_HERE, 
                name:'access_token_secret'
            },
            function(cookie){
                if(cookie){ 
                    access_token_secret = cookie['value'];
                    Interact();
                } else{ 
                    Login();
                }
            });
        }
        function Interact(){
            alert(access_token);
            xhr = new XMLHttpRequest();
            xhr.open("GET", URL_GOES_HERE, true);
            xhr.onreadystatechange = function() {
              if (xhr.readyState == 4) {
                    document.write(xhr.responseText);
              }
            }
            xhr.send();
        }
    </script>


<body onload="cookieHandlerStep1(),cookieHandlerStep2(),Interact()">

Could possibly have the functions executing out of sequence?

Upvotes: 0

Views: 346

Answers (1)

David Tang
David Tang

Reputation: 93674

They're not firing out of order. You've provided callbacks to chrome.cookies.get which are not guaranteed to be called before the rest of the code. The first function returns before the callbacks are fired, and the next two (cookieHandlerStep2() and Interact()) get called.

However, in these callbacks, cookieHandlerStep1() is already calling cookieHandlerStep2() which then calls Interact() - so I presume what you actually want in your onload is just the first function to initiate the chain:

<body onload="cookieHandlerStep1()">

Upvotes: 2

Related Questions