在窗口对象上调用focus()时面临IE11的问题

时间:2014-07-07 07:47:28

标签: javascript window internet-explorer-11

尝试在IE11浏览器上运行以下简单代码:

<!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>

问题:在IE11上,它给出了错误陈述&#34; 无法获得属性&#39;焦点&#39;未定义或空引用&#34;

2 个答案:

答案 0 :(得分:3)

这个答案已经很晚了,但我想我会发布它,以防将来有人遇到这个问题。

根据答案:https://stackoverflow.com/a/7025648/1600090, 和我自己的经验,一个可能的原因可能是你试图在另一个启用了保护模式的互联网区域中打开一个窗口。默认情况下,IE11为Internet和受限制区域启用保护模式,但为本地Intranet和可信站点禁用它。因此,例如,如果您的本地Intranet区域中正在运行您的页面(和/或站点),并且您尝试在Internet区域中打开一个新窗口,则window.open将返回空引用。如果正在启动新窗口的页面/站点位于Internet区域,根据我的经验,window.open将返回一个引用。所以,@ ssut在jsfiddle中的例子是可行的,因为jsfiddle.com和google.com可能都在同一个区域(我假设互联网区域)。

答案 1 :(得分:2)

请检查变量范围。这个问题不是浏览器的问题。

在代码var thewin = window.open(..函数中ButtonClick2,但window.thewin.focus();指向window对象的thewin变量。

将代码更改为thewin.focus();,然后才能完美运行。

新代码:

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>