Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does IE11 throw an error when using window.onbeforeunload?

I've broken my problem down to the following simple code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>IE test</title>
    <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
    <script type="text/javascript" charset="utf-8">
      $( document ).ready(function() {
        $('.js-click').click(function(e){
          window.location.href = 'http://www.google.com/';
        });
        window.onbeforeunload = function(e){
          return 'moving on';
        };
      });
    </script> 
  </head>
<body>
  <a href="#" class="js-click">Google</a>
</body>
</html>

This works as expected in chrome without warning or error, but in IE11 it throws the following error when you choose "Stay on this Page":

File: 10.0.1.126:8080, Line: 10, Column: 11

Any idea why?

like image 978
Ricky Nelson Avatar asked Jul 03 '15 04:07

Ricky Nelson


1 Answers

Actually the error comes from:

window.location.href = 'http://www.google.com/';

And this is just speculation, but I believe the developers of IE wanted to be able to catch when the user decides not to follow the link. Thus, you can actually try-catch this block and you'll know when the user didn't get redirected (as a result of onbeforeupload).

try {
    window.location.href = 'http://www.google.com';
} catch (error) {
    alert("Y U NO REDIRECT");
}

If you console.log(error) you'll see that there's no error message, and the error number is -2147467259.

like image 51
Dave Chen Avatar answered Oct 05 '22 01:10

Dave Chen