首页 > 解决方案 > 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

标签: javascripthtmliframestripe-paymentspostmessage

解决方案


没有什么会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>


推荐阅读