0

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.

Guillaume
  • 47
  • 1
  • 2
  • 7
  • Its working.. I have called the function 2 from a setTimeout and test with firefox and check in console with preserve option enable. An found that it was working properly. – Abhisek Malakar Aug 14 '15 at 12:39
  • I have no influence over function2. I can only change function 1. I will add that in the description. The point is that it seems the event don't fire if your body is not loaded. Just wondering then how to do it without those events. – Guillaume Aug 14 '15 at 12:40
  • Can you please explain what is your requirement. – Abhisek Malakar Aug 14 '15 at 12:49
  • I only have control over function1(). – Guillaume Aug 14 '15 at 12:53
  • Not clear with your requirement, but try addEventListener since direct event handlers like the one you used could be overridden if there is another handler defined later. Javascript is Just in time compiled remember. –  Aug 14 '15 at 16:30
  • You can see in the code sample reproducing my issue I am not defining any other handler. In any case I tried the above with addEventListener and it doesn't work as well. – Guillaume Aug 18 '15 at 08:43

1 Answers1

0

'pagehide' event will trigger in this case instead of 'beforeunload'