窗口打开者 | 在Chrome中无法工作

4
我有两个HTML页面。我正在从子窗口调用父窗口。所有的东西都很好,但在Chrome浏览器中失败了。请告诉我原因。
test1.html:-
<html>
<head>
<title>Compose</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<SCRIPT>
function test(){
//alert('');
var win = window.open('../login/test2.html',"","height=700,width=800");
}
function test1(){
alert('test1');
}
</SCRIPT>
</head>
<body>

<input type="button" value="click" onclick="test();" />             
</body>
</html>

test2.html:-

<html>
<head>
<title></title>
<SCRIPT>
function opener1(){
try{
    if(window.opener != null && !window.opener.closed)
    {

    }
    window.opener.test1();
    }catch(e){ alert(e.description);}
}
</SCRIPT>
</head>
<body oncontextmenu="return false"  ondragstart="return false" onload="opener1();">
<h1>Test Page</h1>

</body>
</html>

从test2.html调用test1.html中的方法不起作用,有什么解决方案吗?感激不尽,谢谢。
4个回答

8

只能使用parent变量来访问父窗口。对opener1函数进行以下修改可以实现这一点。

function opener1(){
    try{
        if(parent.window.opener != null && !parent.window.opener.closed)
        {
          parent.window.opener.test1();
        }

    }catch(e){ alert(e.description);}       
}

1
为什么这里涉及到一个“父级”? - jfriend00
嗨,Anurpur,问题仍然存在...警告显示未定义。 - sree
因为您想访问从第二个窗口(test2.html)调用的窗口(test1.html)的函数。 所以test1.html是test2.html的父窗口。这就是Javascript的操作方式。简单地调用窗口是指当前窗口。 - anurupr
有趣的是,这边看起来没问题。你确定你在test2.html中的opener1函数做出了改变吗? - anurupr
<html> <head> <title></title> <SCRIPT> function opener1(){ try{ if(parent.window.opener != null && !parent.window.opener.closed) { } parent.window.opener.test1(); }catch(e){ alert(e.description);} } </SCRIPT></head> <body oncontextmenu="return false" ondragstart="return false" onload="opener1();"> <h1>测试页面</h1> </body> </html> - sree
显示剩余5条评论

0

对我来说代码似乎是没问题的。如果你捕获了一个异常,可以将其记录到控制台上以获取出错信息。确保test1.html和test2.html的域匹配,否则会出现安全异常。


错误信息为:阻止了一个源为“null”的框架访问跨源框架。 - sree
这意味着您的父子窗口域不匹配。此外,如果从文件系统打开HTML,则无法正常工作。 - Oskars Pakers

0
你可以尝试我的代码:
window.opener.document.location.href = url;

这将在IE和Chrome中都能正常工作。

window.opener.location.href = 'test.html';

这将打开名为 "test.html" 的页面。

一旦它被打开,您可以关闭父窗口。

如果有效,请不要忘记将我的答案标记为正确。


-1
这是因为在像或Chrome这样的设备上,windows对象的opener属性为空。

1
我正在使用Windows 7下的Chrome 64,"window.opener"根本不为null。 - Elo
@Elo 对我来说是 null。 - aderchox

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接