[英]Can I communicate between two local html files using javascript?
I have two local .html files in the same folder.我在同一个文件夹中有两个本地 .html 文件。 One page opens a window with the other page, and attempts to call a function in the newly opened window.一个页面与另一个页面一起打开一个窗口,并尝试在新打开的窗口中调用一个函数。 However, the function call fails, and I get this in the console:但是,函数调用失败,我在控制台中得到了这个:
Unsafe JavaScript attempt to access frame with URL file:///***/A.html from frame with URL file:///***/B.html.不安全的 JavaScript 尝试从带有 URL file:///***/B.html 的框架访问带有 URL file:///***/A.html 的框架。 Domains, protocols and ports must match.域、协议和端口必须匹配。
This happens on both Chrome and Webkit (Mac).这发生在 Chrome 和 Webkit (Mac) 上。 Is there any way I can either: disable the cross-domain checks for the file:// protocol, or call a javascript function in a different local file?有什么办法可以:禁用 file:// 协议的跨域检查,或者在不同的本地文件中调用 javascript 函数?
You can use window.postMessage to do something like this:你可以使用 window.postMessage 做这样的事情:
The initial window html file:初始窗口 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 for the second window:第二个窗口的 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>
Here's a good reference for window.postMessage .这是window.postMessage的一个很好的参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.