IE11-facing issue while calling focus() on window

2019-08-31 03:29发布

问题:

Trying to run a following simple code on IE11 browser:

<!DOCTYPE html>
<html>

<head>
  <title>Popup Example</title>
  <script>
function ButtonClick2() {
var thewin = window.open("http://www.google.com",'thewin','width=400, height=420,status=no');            
window.thewin.focus();

        }

  </script>
</head>

<body>
   <button onclick="ButtonClick2()">Click Me!</button>
</body>

</html>

ISSUE:On IE11 it gives the error statement "Unable to get property 'focus' of undefined or null reference"

回答1:

This answer's late, but I thought that I'd post it just in case somebody came across this question in the future.

According to the answer here: https://stackoverflow.com/a/7025648/1600090, and my own experience, one possible cause could be that you're trying to open a window in a different internet zone for which Protected Mode is enabled. By default, IE11 enables Protected Mode for the Internet and Restricted zones but disables it for Local Intranet and Trusted Sites. So, for example, if your page (and/or site) are running in your Local Intranet zone and you're trying to open a new window in the Internet zone, window.open is going to return a null reference. If the page/site which is launching the new window is in the Internet zone, in my experience, window.open will return a reference. So, @ssut's example in jsfiddle is going to work because jsfiddle.com and google.com are probably both in the same zone (I'm assuming the Internet zone).



回答2:

Please check the variable scope. This issue is not browser's problem.

In your code, var thewin = window.open(.. in the ButtonClick2 function, but window.thewin.focus(); is point to window object's thewin variable.

Change the code to thewin.focus(); then it works perfectly.

New code:

PE html>
<html>

<head>
  <title>Popup Example</title>
  <script>
function ButtonClick2() {
var thewin = window.open("http://www.google.com",'thewin','width=400, height=420,status=no');            
thewin.focus();

        }

  </script>
</head>

<body>
   <button onclick="ButtonClick2()">Click Me!</button>
</body>

</html>