我在Chrome中打开一个窗口/标签:
childWin = window.open('child.html');
然后我尝试在孩子中调用一个函数:
childWin.objReceiver( {foo: 'blah', zoo: 'bing'} );
但我在Chrome内容中遇到以下2个错误(Firefox工作正常):
Unsafe JavaScript attempt to access frame with URL file:///C:/Users/Slava/Documents/AMP/app_poc/test/child.html from frame with URL file:///C:/Users/Slava/Documents/AMP/app_poc/test/index.html#. Domains, protocols and ports must match.
Uncaught TypeError: Property 'objReceiver' of object [object Window] is not a function
请告知。
答案 0 :(得分:3)
在测试此类事物时,您希望从真实的Web服务器进程提供文档(因此URL为http://...
)。适用于本地资源的安全策略浏览器(您的file:///...
URL)可能比Web资源的同源策略更具限制性。 (特别是:某些浏览器将本地文件视为与任何源不匹配,甚至是同一目录中的另一个本地文件。)
只需在您的计算机上安装一个简单的Web服务器(或复杂的服务器,如果您愿意:-))。
另一件需要注意的事情是,您可能无法立即调用子窗口上的函数,因为窗口可能尚未加载。所以你可以看到孩子出现objReceiver
,如下:
jQuery(function($) {
$("#target").click(function() {
// Open the window
var wnd = window.open("http://jsbin.com/ofigis/1");
// Give it a 10th of a second to appear
display("Window open, waiting for it to appear...");
setTimeout(watchForWindow, 100);
// Our function watching for it
function watchForWindow() {
// Is it there?
if (wnd.objReceiver) {
// Good, we're done waiting -- send the message
wnd.objReceiver({
foo: "blah"
});
display("Message sent");
}
else {
// Not there yet, keep waiting...
setTimeout(watchForWindow, 0);
}
}
});
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
});
(我在那里使用jQuery只是为了方便,没有一个基本位依赖它)