masterFly masterFly - 1 month ago 8
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
alert
just before the redirect code line. I got the
alert
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?

Edit



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

$scope.$watch(
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( e.data.action ){
case 'redirect':
var url = e.data.value;
//alert("**");
window.location.href = url;
//window.location = url;
//window.location.replace(url);
//$(location).attr('href',url);
console.log("INSIDE REDIRECT: ("+url+")");
break;
default: break;
}
}, false);


Hope this satisfies the comments!

Answer

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);
Comments