iframe跨域解决方案-2(postMessage)

1.父域页面(a.html):act/msg/evalStr 为自定义属性

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>
    <input type="text" id="textValue"/>
    <input type="button" value="获取跨域的页面内容" onclick="method1()"/>
    <br/>
    <hr/>
    <iframe src="http://127.0.0.1:8821/b.html" width="500" height="500" id="iframe1" name="iframe1"></iframe>
<script>
function method1(){
 	var frm = document.getElementById("iframe1");
    frm.contentWindow.postMessage({
        act: 'article',  // 自定义的消息类型、行为,用于switch条件判断等。。
        msg: {
        	evalStr: 'alert("跨域成功!")'
        }
    },"*");
}
var OnMessage = function (e) {
	if (e.data.act == 'response') {
		var textValue = document.getElementById("textValue");
		textValue.value=e.data.msg.reportFormId;
    } else {
        alert('未定义的消息: '+ e.data.act);
    }
}
if (window.addEventListener) {  // all browsers except IE before version 9
    window.addEventListener("message", OnMessage, false);
} else {
    if (window.attachEvent) {   // IE before version 9
    	window.attachEvent("onmessage", OnMessage);
    }
}
</script>
</body>
</html>

2.子域页面(b.html):

<!DOCTYPE html>
<html>
<head>
	<title>子域</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta name="viewport" content="width=width-device,initial-scale=1.0,user-scalable=no" />
</head>
<body>
<div><h1>这是子域内容</h1></div>
<script>
var reportFormId = 'www.thunisoft.com';
var OnMessage = function (e) {
	if (e.data.act == 'article') {
		//触发编辑页面的保存事件或者添加eval方法
		eval(e.data.msg.evalStr);
        // 向父窗框返回响应结果
        window.parent.postMessage({ 
            act: 'response',
            msg: {
            	reportFormId: reportFormId //报表id
            }
        }, '*');
    } else {
        alert('未定义的消息: '+ e.data.act);
    }
}
if (window.addEventListener) {  // all browsers except IE before version 9
    window.addEventListener("message", OnMessage, false);
} else {
    if (window.attachEvent) {   // IE before version 9
    window.attachEvent("onmessage", OnMessage);
    }
}
</script>
</body>
</html>
posted @ 2021-01-23 13:46  believexin  阅读(118)  评论(0编辑  收藏  举报