我在 iframe 中触发自定义事件并从父文档中检测到它时遇到了一些问题。 iframe 和父文档具有相同的来源(相同的协议(protocol)、相同的主机、相同的端口)。
有什么建议吗?
最佳答案
我遇到了类似的问题,用window.postMessage
解决了。
目前,该 API 仅支持传递字符串,但如果您修改您的解决方案,它会非常强大。更多详情 here
来自源页面(被 iframe 使用):
postMessage API 需要 2 个参数 - 消息、目标
例如:window.parent.postMessage("HELLO_PARENT", 'http://parent.com');
从父页面(包含 iframe。例如 Container):
像往常一样添加一个事件监听器
window.addEventListener('message', handleMessage, false);
使用 event.origin 检查定义您的函数(为了安全)\
function handleMessage(event) { if (event.origin != "http://child.com") { return; } switch(event.data) { case "HELLO_PARENT": alert("Hello Child"); break; } }
关于javascript - 触发从 iframe 到父文档的自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12967616/