masterFly masterFly - 1 year ago 92
jQuery Question

Javascript redirect strange behavior

I am trying to do a JavaScript redirect inside an event handler. The event handler receives the message from child and when I receives the message I want to do a simple JS redirect.

I have tried the following:

  1. window.location.href = url;

  2. window.location = url;

  3. window.location.replace(url);

  4. $(location).attr('href',url);

But none of the above did the redirecting. Then I put an
just before the redirect code line. I got the
and when I click on it, the redirect worked.

So with alert it works, but when I remove the alert it is not redirecting.

Can you guys help me to figure this out? Any aspects that I should look at? Any clues?


This is the code block I used to send message to parent (which is inside an angular controller)

function () { return vm.redirect; },
function () {
window.parent.postMessage({action: 'redirect', value:vm.redirect_url}, "*");

And here is the code that I used to catch the message and do redirect.

var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

eventer(messageEvent, function (e) {
switch( ){
case 'redirect':
var url =;
window.location.href = url;
//window.location = url;
console.log("INSIDE REDIRECT: ("+url+")");
default: break;
}, false);

Hope this satisfies the comments!

Answer Source

As it redirects when having the alert before the code, so I think it may work by using setTimeout as following:

setTimeout(function(){window.location.href = url;},0);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download