您的位置:首页 > Web前端 > JavaScript

利用postmessage间接实现iframe跨域调用父页面js函数

2016-02-24 17:36 681 查看
父页面html代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
window.onload = function () {
//添加监听事件。
if (typeof window.addEventListener != "undefined")
window.addEventListener("message", func, false);
else if (typeof window.attachEvent != 'undefined')//兼容不支持addEventLinstener的IE。
window.attachEvent("onmessage", func);
}
//被调用的函数。
function invocationTarget(msg) {
if (msg)
alert(msg);
else
alert("~~~");
}
//监听事件回调函数。
function func(e) {
if (e.data.action == true)
invocationTarget(e.data.value);
}
</script>
</head>
<body>
<iframe src="子页面域名/HtmlPage.html" style="border:0px"></iframe>
</body>
</html>


子页面html代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
function invocation() {
var data = { action: true, value: 'hello world' };
//第一个参数表示要传递的参数,第二个参数表示要传递到的目标。
window.parent.postMessage(data, "父页面域名/HtmlPage.html");
}
</script>
</head>
<body>
<input onclick="invocation();" type="button" />
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息