My redirect in javascript somehow gets "hijacked" and I don't understand how.
Previous developer (who is no longer working with the company) on page load initialized onbeforeunload
event like so:
window.onbeforeunload = function() {
if(<some condition>)
<make some ajax request>
}
Now I have a requirement where I need to do a redirect, like so:
window.location = "https://duckduckgo.com"; // just some external url
Both pieces of code above are being reused by multiple pages. In all pages redirect works, except one. Only on 1 page after my debugger steps over my redirect and then reaches this point
window.onbeforeunload = function() {
if(<some condition>)
<make some ajax request>
--> }
I do a step over and instead of getting redirected to https://duckduckgo.com
I get redirected to a different internal page in my application.
Looks like something is happening in javascript between onbeforeunload
and my redirect but I can't understand what it is. I don't even understand how I can continue debugging this.
- How is that possible?
- What can I do to debug this farther?
- Is there some kind of onbeforebeforeunload
event or something?
Update.
"onbeforeunload" and "redirect" snippets of code are located in two different files, kind of like so:
File A.js:
$(function(){
...
window.onbeforeunload = function() {
if(<some condition>)
<make some ajax request>
}
...
});
File B.js
var Obj1 = (function(){
return {
init(): function() {
this.Obj2.init();
}
}
});
Obj1.Obj2 = (function(){
var process = function(){
...
window.location = "https://duckduckgo.com";
...
}
return {
run: process,
init: function(){
...
}
}
});
and then at some point process function gets called:
Obj1.Obj2.run();
Update 2:
I put debugger;
in and out of every single piece of code where I saw "beforeunload" like so in my entire project:
$(this).on("beforeunload", function(){
...
});
Not a single breakpoint got hit.
Update 3.
I added the following lines of code prior to redirect:
window.onunload = function(){
debugger; // Not hit
};
window.onbeforeunload = function(){
debugger; // <-- Hit 1st
};
$(window).on("beforeunload", function() {
debugger; // <-- Hit 2nd
});
$(window).on("unload", function() {
debugger; // Not hit
});
window.location = "https://<url>";
As comments above describe, first window.onbeforeunload
gets hit, then $(window).on("unload"...
and then redirect to internal (not the one that I need) page happens.