我在同一个文件夹中有两个本地.html文件。一个页面打开另一个页面的窗口,然后尝试在新打开的窗口中调用一个函数。然而,函数调用失败了,我在控制台中得到了这样的结果:
不安全的file:///***/A.html试图从具有URL file:///***/B.html.的帧访问框架域、协议和端口必须匹配。
这种情况发生在Chrome和Webkit (Mac)上。是否有任何方法可以:禁用对文件的跨域检查:// protocol,或者在不同的本地文件中调用javascript函数?
发布于 2012-11-24 23:21:56
您可以使用window.postMessage进行如下操作:
初始窗口html文件:
<!DOCTYPE html>
<html>
<head>
<script>
var otherWindow;
function openOther() {
otherWindow = window.open("other.html", "otherWindow");
}
function otherFunc() {
otherWindow.postMessage("otherFunc", "*");
}
</script>
</head>
<body>
<div onclick="openOther()">Open the other window</div>
<div onclick="otherFunc()">Call the other window's function</div>
</body>
</html>第二个窗口的Html:
<!DOCTYPE html>
<html>
<head>
<script>
window.addEventListener("message", function(event) {
alert("The other window's function executed.");
}, false);
</script>
</head>
<body>
<div>This is the other window.</div>
</body>
</html>这里是window.postMessage的一个很好的参考。
https://stackoverflow.com/questions/13545883
复制相似问题