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

来源:互联网 发布:python 源码安装包 编辑:程序博客网 时间:2024/04/27 15:57

父页面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>


0 0
原创粉丝点击