![](/img/trans.png)
[英]Can two javascript files communicate through referencing in html body?
[英]Can I communicate between two local html files using javascript?
我在同一個文件夾中有兩個本地 .html 文件。 一個頁面與另一個頁面一起打開一個窗口,並嘗試在新打開的窗口中調用一個函數。 但是,函數調用失敗,我在控制台中得到了這個:
不安全的 JavaScript 嘗試從帶有 URL file:///***/B.html 的框架訪問帶有 URL file:///***/A.html 的框架。 域、協議和端口必須匹配。
這發生在 Chrome 和 Webkit (Mac) 上。 有什么辦法可以:禁用 file:// 協議的跨域檢查,或者在不同的本地文件中調用 javascript 函數?
你可以使用 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的一個很好的參考。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.