跨域的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>