我正在尝试使 HTML postMessage 功能正常工作?
我找到了一些给出示例的站点,但由于某种原因而苦苦挣扎。
2 页的代码如下所示,如有任何帮助,将不胜感激。
谢谢和问候, 瑞安
测试.php
<iframe src="postmessage-target.html" id="iframe"></iframe>
<form id="form">
<input type="text" id="msg" value="Message to send"/>
<input type="submit"/>
</form>
<script>
window.onload = function(){
var win = document.getElementById("iframe").contentWindow;
document.getElementById("form").onsubmit = function(e){
win.postMessage( document.getElementById("msg").value );
e.preventDefault();
};
};
</script>
postmessage-target.html
<div id="test">Send me a message!</div>
<script>
document.addEventListener("message", function(e){
document.getElementById("test").textContent =
e.domain + " said: " + e.data;
}, false);
</script>
再次提前感谢。
瑞安
更新
根据用户的建议,这是否正确?
测试.html
<iframe src="postmessage-target.html" id="iframe"></iframe>
<form id="form">
<input type="text" id="msg" value="Message to send"/>
<input type="submit"/>
</form>
<script>
window.onload = function(){
var win = document.getElementById("iframe").contentWindow;
document.getElementById("form").onsubmit = function(e){
win.postMessage( document.getElementById("msg").value, "*");
e.preventDefault();
};
};
</script>
postmessage-target.html
<div id="test">Send me a message!</div>
<script>
document.addEventListener("message", function(e){
document.getElementById("test").innerHTML = e.origin + " said: " + e.data;
}, false);
</script>