layer弹窗:top.layer弹窗到父页面跨域解决办法

在这里插入图片描述

跨域的iframe里的layer弹窗会报错

DOMException: Blocked a frame with origin “http://localhost:5556” from accessing a cross-origin frame.
at HTMLButtonElement. (http://localhost:5556/2.html:19:15)
at HTMLButtonElement.dispatch (https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js:2:5418)
at HTMLButtonElement.y.handle (https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js:2:2126)

可以在这下载,也可以复制下边代码

子页面postMessage发送配置到父页面

不能发送top或者发送window,甚至是配置内的function属性都不能发送,只能发送简单的配置对象

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script>
  </script>
</head>
<body>
  <button>弹窗</button>
  <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
  <script src="https://www.layuicdn.com/layer-v3.1.1/layer.js"></script>
  <script>
    $(function(){
      $('button').click(function(){
        try {
          // 如果top.layer不跨域,那么正常弹窗
          top.layer.open({
            title: '弹窗',
            shadeClose: false,
            shade: 0.3,
            maxmin: true, //开启最大化最小化按钮
            area: ['1200px', '600px'],
            offset: 'auto',
            content: '我是子页面'
          });
        } catch (error) {
          // 报错后拿到配置,发送到父页面
          var option = {
            title: '弹窗',
            shadeClose: false,
            shade: 0.3,
            maxmin: true, //开启最大化最小化按钮
            area: ['1200px', '600px'],
            offset: 'auto',
            content: '我是子页面'
          }
          //不能发送top或者发送window,甚至是配置内的function属性都不能发送,只能发送简单的配置对象
          window.top.postMessage(option, '*')
        }
      })
    })
  </script>
</body>
</html>

父页面接收配置

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <iframe src="http://localhost:5556/2.html" frameborder="0"></iframe>
  <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
  <script src="https://www.layuicdn.com/layer-v3.1.1/layer.js"></script>
  <script>
    //监听iframe传参
    window.addEventListener('message', function(e){
      console.log(e)
      layer.open(e.data)
    }, false)
  </script>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值