javascript - Parent 中的 AddEventListener 和 iframe 中的 postMessage 不能一起工作
问题描述
我在开发一项功能时尝试遵循Stripe 文档,但我遇到了网页和 iframe之间的通信问题。
索引.html:
<!DOCTYPE html>
<body>
parent<br>
<iframe src="./sca-iframe.html" width="100" height="100" ></iframe>
</body>
<script>
debugger
function on3DSComplete() {
debugger
console.log("Event received!!!!")
}
window.addEventListener('3DS-authentication-complete', on3DSComplete, false);
</script>
</html>
框架:
<!DOCTYPE html>
<body>
iframe
<script>
debugger
window.top.postMessage('3DS-authentication-complete');
console.log("postMessage('3DS-authentication-complete')")
</script>
</body>
</html>
哪里有问题?我找不到它了 :(
Plunkr:http://embed.plnkr.co/0CLhHnncF4Ntsif0u9zY/ http://run.plnkr.co/preview/cjzi23ugh0005315uxn7fj6od/
Github 示例仓库:https://github.com/noisy/strie-customize-the-3d-secure-ui-test
解决方案
没有什么会3DS-authentication-complete
在这里触发事件。
你想要的是听message
事件。但是,由于此事件可能由多个来源触发,因此您最好检查消息内容的完整性。
所以你最终会得到类似的东西:
function on3DSComplete() {
console.log("Event received!!!!")
}
window.addEventListener('message', function(event) {
if(event.origin === location.origin &&
event.data === "3DS-authentication-complete") {
on3DSComplete();
}
});
function on3DSComplete() {
console.log("Event received!!!!")
}
function waitFor3DSMessage(event) {
if(event.data === "3DS-authentication-complete") {
on3DSComplete();
// in case we don't need to listen anymore
window.removeEventListener('message', waitFor3DSMessage);
}
}
window.addEventListener('message', waitFor3DSMessage);
const framecontent = `<!DOCTYPE html>
<body>
iframe
<script>
// in StackSnippet we need to use 'parent', because 'top' is the actual Q/A page
parent.postMessage('3DS-authentication-complete', '*');
<\/script>
</body>
</html>`;
document.getElementById('frame').src = URL.createObjectURL(new Blob([framecontent], {type: 'text/html'}));
parent
<iframe id="frame"></iframe>
推荐阅读
- javascript - 自定义嵌入印迹无法重新实例化已经存在的对象
- java - 如何在java中使用两个哈希图计算比率
- python - Dash:如何更新回调中的数百个元素?
- java - 如何使用正则表达式在 Java 中查找子字符串?
- bash - 在 bashrc 中保存常见的 Grep 模式
- reactjs - 在 Sider 内的 Ant Design 菜单中重置 openKeys 的问题
- android - 如何处理单击 ListView 项中的两个 ImageView
- javascript - 单击时将多个变量记录到数组中
- ruby-on-rails - Rails + nginx + 独角兽 = 502 错误网关
- swift - SwiftUI – 导航栏“isTranscluent”属性在 iPad 上崩溃