Search code examples
javascriptgoogle-chromehrefwindow.location

How can I navigate to a different href first, then let the code continue, using just JavaScript?


When I enter this code into the console on Chrome browser, the alert comes first, followed by the new href, even though the 'window.location.replace()' is in-front of the alert:

window.location.replace('http://stackoverflow.com/');
alert('hi');

I would like to know how to navigate to the new page, and then let the alert happen. How would I do that?


Solution

  • I would like to know how to navigate to the new page, and then let the alert happen. How would i do that?

    You can't. The JavaScript environment in browsers is tied to the page. When the page is torn down, the environment is torn down with it. Even if you were to do something like this:

    // Example of something that DOESN'T work
    window.location.replace('http://stackoverflow.com/');
    setTimeout(function() {
        alert('hi');
    }, 100);
    

    ...the timer callback would never fire, because the environment is torn down before it has a chance to.

    All you can do is pass information to the next page so that code on that next page runs.