【问题标题】:AddEventListener in Parent and postMessage in iframe doesn't work togetherParent 中的 AddEventListener 和 iframe 中的 postMessage 不能一起工作
【发布时间】:2019-08-19 07:13:28
【问题描述】:

我正在尝试关注Stripe documentation,同时开发一项功能,但我遇到了网页和 iframe 之间的通信问题。

index.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>

iframe:

<!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

【问题讨论】:

    标签: javascript html iframe stripe-payments postmessage


    【解决方案1】:

    这里没有什么会触发3DS-authentication-complete 事件。

    你想听的是message event。但是,由于此事件可能由多个来源触发,因此您最好检查消息内容的完整性。

    所以你最终会得到类似的东西:

    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>

    【讨论】:

      【解决方案2】:

      在发布消息时尝试window.parent.postMessage('3DS-authentication-complete', '*');

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多