在我的 html 页面(file:///C:/Users/NEC/Desktop/test.html)中,有 javascript 变量(或输入文本字段)和调用其他主机的 iframe
(本地主机:8081/TProject/sample.html)。
在 test.html 中
<iframe src="localhost:8081/TProject/sample.html" ></iframe><br/>
<input type="text" id="output" ><br />
并且,在我的iframe
中显示的sample.html中,有以下javascript
代码来更改父窗口输入文本的值。
function setData() {
window.parent.getElementById("output").value = "hello";
}
错误消息是:
Uncaught SecurityError: Blocked a frame with origin "localhost:8081" from
accessing a frame with origin "null". The frame requesting access has a protocol of
"http", the frame being accessed has a protocol of "file". Protocols must match.
如何将值(javascript 变量)从在线服务器传递到离线 html 页面?
最佳答案
谢谢您的回答。 现在我可以使用“window.parent.postMessage()”解决我的问题。
从 iframe 的本地主机服务器页面使用以下内容发送消息
window.parent.postMessage({ message: 'successfully connected'}, "*");
并从离线页面捕获该消息
window.addEventListener('message', function(event) {
document.getElementById("output").value = event.data.message;
}, false);
关于javascript - 如何从本地主机的iframe将数据设置为离线html文件的父窗口变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21745793/