码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2021-01-25 11:20:46      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:view   ice   cli   mes   soft   form   成功   scale   tac   

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>

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

标签:view   ice   cli   mes   soft   form   成功   scale   tac   

原文地址:https://www.cnblogs.com/believexin/p/14317414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!