Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does setting window.location.href not stop script execution

The following code changes the location to www.bing.com regardless of wether redirect is 1 or any other number. If redirect is 1, it logs "is redirecting" and then redirects to www.bing.com. My best guess is that when href is set a change-event is triggered, but it takes some ticks before it executes. Meanwhilethe first line of code after is still executed. Or? do anyone what happens?

if (redirect == 1) {
    console.log("is redirecting");
    window.location.href = "http://www.google.com";
}

window.location.href = "http://www.bing.com";
like image 264
Bildsoe Avatar asked Apr 04 '16 09:04

Bildsoe


3 Answers

You are setting a property, not calling a method, the difference is important:

window.location.href = "something";

Javascript works asyncronous and event based, that means the browser doesn't check for the window location changing right when you set the property, but some unpredictable time later.

Sometimes you want exit-events to be triggered or fired when the location changes.

When you compare this to the HTTP location header, the behaviour is the same. Sometimes you want for example PHP scripts to continue even you send the location change header.

like image 108
Daniel W. Avatar answered Nov 14 '22 03:11

Daniel W.


I would say the behaviour is undefined.

When you set the expected url to window.location.href, the current page will actually be in the dying state. And the result of the code written after that is simply unpredictable.

like image 4
Lewis Avatar answered Nov 14 '22 02:11

Lewis


That's because everything after the if is executed as well, but it looks like there's a difference between Chrome and FF (haven't tested in IE).

Example code:

var redirect = 1;

if (redirect == 1) {
    console.log("is redirecting");
    document.location.assign('https://developer.mozilla.org/');
}

alert('go');
document.location.assign('https://www.bing.com/');

In Chrome 'go' is alerted, and you're redirected to bing.com. In Firefox, 'go' is alerted, but you're redirected to MDN.

I think, the best thing to do is to wrap the other stuff in an else.

like image 2
Pimmol Avatar answered Nov 14 '22 01:11

Pimmol