使用postMessage解决iframe跨域问题

2018-07-02  本文已影响0人  QRFF
<!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>
上一篇下一篇

猜你喜欢

热点阅读