The*_*age 3 html javascript iframe scope arguments
MainWindow创建一个ChildWindow需要利用的JavaScript对象。
我的MainWindow.html目前看起来像这样
<html>
<body>
<script>
var varObject = {type:"Error", message:"Lots"};
</script>
<iframe class="child" src="ChildWindow.html"></iframe>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
ChildWindow.html看起来像这样
<html>
<body>
<script>
console.log(varObject.type); // goal is to log "Error"
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
ChildWindow试图使用在MainWindow中创建的对象,这当然不能,因为我还不知道如何传递它。
我已经尝试过使用Google,但是我发现大多数解决方案都涉及将值作为字符串而不是作为变量传递。
小智 6
请看一下下面的代码:
<html>
<body>
<script>
var varObject = {type:"Error", message:"Lots"};
var child = document.getElementsByClassName("child")[0];
var childWindow = child.contentWindow;
childWindow.postMessage(JSON.stringify(varObject),*);
</script>
<iframe class="child" src="ChildWindow.html"></iframe>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
在 ChildWindow.html 中
<html>
<body>
<script>
function getData(e){
let data = JSON.parse(e.data);
console.log(data);
}
if(window.addEventListener){
window.addEventListener("message", getData, false);
} else {
window.attachEvent("onmessage", getData);
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你 :)
只需将对象分配给windowiframe 即可传递对象。
在父窗口中:
var frame = document.querySelector("iframe");
frame.contextWindow.object_of_interest = object_of_interest;
Run Code Online (Sandbox Code Playgroud)
在iframe的窗口中
var frame = document.querySelector("iframe");
frame.contextWindow.object_of_interest = object_of_interest;
Run Code Online (Sandbox Code Playgroud)