Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `alert("2nd");` execute before `window.history.back();`?

Tags:

javascript

When I ran the following two JavaScript commands...

> window.history.back(); alert("2nd");

...I was expecting the window to go to the previous page, and then display the alert. What happens is "2nd" actually pops up first, and then the window goes back. If I reverse them like this...

> alert("2nd"); window.history.back();

...the commands still execute in the same order. What don't I understand about JavaScript control flow? How would I get window.history.back(); to run first?

like image 677
popedotninja Avatar asked Oct 01 '22 04:10

popedotninja


1 Answers

Well, it makes sense that the alert is not displayed after the other page has loaded. The script is part of the loaded page, so if that would work, it would mean you could inject javascript in the previous page, which is of course undesirable.

So as I see it, there are 3 possibilities:

  1. The back function is blocking and works immediately, navigating to a previous page, and terminate the running script. This obviously isn't happening, otherwise you wouldn't get the alert at all.
  2. The back function works immediately, but the script is only terminated when the browser has enough information to start loading the other document. This doesn't seem to be the case. If it were, the browser would probably load the document in the background while the alert is open, but that doesn't happen.
  3. The back function just signals the browser to go back, and the script keeps running until it's idle before that request is actually fulfilled. This seems to be the case. Navigation only starts when the alert is closed and the script ends. (At least in Chrome).

Anyway, if you want this to work, you'll have to call alert from the page you are navigating to.

like image 102
GolezTrol Avatar answered Oct 06 '22 00:10

GolezTrol