今天在使用parent.fn()调用父页面方法时发现并没有成功调用到父级iframe中的方法,后来发现是两个iframe并不在同一域名下,在网上查过后,发现H5中message方法恰好支持,闲话不多说了,上代码
父界面
<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><script type="text/javascript" src="js/jquery-1.11.3.min.js"></script><script type="text/javascript" src="js/cdIframe.js" ></script></head><body><!--注意该页面在打开时不能使用http://192.168.1.222--><iframe src="http://192.168.1.222:8020/mywork1/new_file.html" width="" height="" id="iframe"></iframe></body><script type="text/javascript">/** receiveMessage (type, callback)* type子页面传值时进行匹配的字段名称* callback(data, node)* node子页面所传的值* * */receiveMessage("istype", function (data, node) {console.log(node)//子页面中所填写类型为"istype"的数据})</script></html>
子页面
<!DOCTYPE html><html><head><meta charset="UTF-8"><script type="text/javascript" src="js/jquery-1.11.3.min.js" ></script><script type="text/javascript" src="js/cdIframe.js" ></script><title></title></head><body><button id="btn">按钮</button><script>/** postMessage(type, data, direction)* param: type content direction* istype父页面接收时进行匹配的字段名称* top标记该数据向父级页面传输* * */postMessage("istype", "这是一个句话", "top")</script></body></html>
以下就是js代码:
/** cdIframe.js* iframe中跨域通信* -8-9* Y J* * *///父窗体中监听消息function receiveMessage (type, callback) {window.addEventListener('message', function(e) {if(e.data.type == type){callback(e.data, e)};});};//子窗体中监听消息function postMessage(type, data, direction) {var post = {type: type,data: data};if(direction == "top"){window.parent.postMessage(post, '*');}else{window.frames[0].postMessage(post,'*');//若是向子页面传值则使用该句};};
以上就是所有的代码了,如果哪里写的不对还请多多指正。
下载地址:/yangjunhouse/dome/tree/master/dome-cdIframe