How do I detect a window.location modification which is made between the <head>
tags?
When I execute the below in the chrome console I get my console.log as expected.
window.onbeforeunload = function(){
console.log("Before Unload");
};
window.location.replace("http://www.google.com");
However If I place this snippet in a js file placed in the <head>
of my page, then my console.log won't appear and it seems that onbeforeunload
and onunload
are never triggered. I am sure the snippet of code is executed properly since I can go through every line with a debugger statement.
How can I detect if there is a location change in the <head>
of the page before my body is loaded? I cannot overwrite window.location.replace since it's unforgeable.
Here is an easy code sample that reproduces my issue
<head>
<script type="text/javascript">
var function1 = function() {
window.onunload = function() {
console.log("onunload");
}
}
var function2 = function() {
window.location.replace("http://www.google.com");
}
function1();
function2();
</script>
</head>
<body>
This is my test
</body>
The limitation I have is that I can only change the content of function1.
Edit: The actual use case is as follow: I have a script in the header of a website. I can write anything I want in this script but I have no control over the rest of the website. In some cases there is a script right after mine which will do a redirection. I need to set a cookie when that's the case.