美文网首页
使用postMessage解决iframe跨域问题

使用postMessage解决iframe跨域问题

作者: QRFF | 来源:发表于2018-07-02 21:58 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <meta http-equiv="X-UA-Compatible" content="ie=edge">
       <title>Document</title>
    </head>
    
    <body>
       <button>
           点击
       </button>
       <div id='iframe1' style='display:none'>
           <span id='gb'> 关闭</span>
           <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
           <script>
               $('#gb').click(function(){
                   layer.alert('确认关闭',function(){
                       layer.closeAll();
                       parent.postMessage( {cardId:'2131',msg: 'close'}, '*');
                   })
               })
           </script>
       </div>
       <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
       <script src='https://cdn.bootcss.com/layer/3.1.0/layer.js'>
       </script>
       <script>
           $('button').click(function () {
               layer.open({
                   type: '1',
                   content: $('#iframe1'),
                   area:['200px','200px']
               })
           })
          function receiveMessageFromIframePage (event) {
              console.log('event :', event);
               if(event.data.msg=='close'){
                   layer.closeAll();
                   // location.reload()
               }
           }
           window.addEventListener("message", receiveMessageFromIframePage, false);
       </script>
    </body>
    
    </html>
    

    相关文章

      网友评论

          本文标题:使用postMessage解决iframe跨域问题

          本文链接:https://www.haomeiwen.com/subject/eifruftx.html