我正在尝试创建小型编辑器,允许用户使用 iframe 编辑 html。因此将 html 字符串作为 data:text/html 传递到 src 中。但通信并未发生在父窗口中。
帮我看看我做错了什么。
index.html
<iframe id="creditMailBody" class="iframe-main-content" src="{{creditMail.content}}"></iframe>
在 html 字符串中
<html>
<head>
</head>
<body>
<p id="editor" contentEditable="true"></p>
</body>
<script>
document.getElementById("editor").addEventListener("input", function() {
console.log("input event fired");
window.parent.postMessage('iframe_message', '*')
}, false);
</script>
</html>
在 Controller 中
window.addEventListener('iframe_message', function() {
console.log('iframe message')
}, true);
最佳答案
拼写错误:
该事件称为message
,而不是iframe_message
:
const frame_content = `<html>
<head>
</head>
<body>
<p id="editor" contentEditable="true">edit me</p>
</body>
<script>
document.getElementById("editor").addEventListener("input", function() {
console.log("input event fired");
window.parent.postMessage('iframe_message', '*')
}, false);
<\/script>
</html>`;
frame.src = 'data:text/html,' + encodeURIComponent(frame_content);
window.addEventListener("message", function() {
// ^-- Here it is "message"
console.log('iframe message')
});
<iframe id="frame"></iframe>
关于javascript - window.parent.postMessage 不适用于 scr ="' 数据 :text/html;charset=utf-8"in iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54402029/