先上模块链接
http://bgcls.gitee.io/webdata/messager.js
本模块能解决以下问题:
- iframe 与 父页面的参数传递
- 可以判断某个iframe是否加载完成
- iframe 与 父页面的交互
- 判断iframe框架是否收到父页面的消息
模块主要函数:
//函数 @mchat
//框架名字 自己随便取名,父页面请设定为host(固定的)
//自定义类型回调 如果send里面类型填除了function和result,都会执行回调函数
//注意,在html网页中,一个网页框架中只能有一个实例,想要二次初始化,请在第一次的时候执行.close(),否则将会初始化失败。
chat=mchat([框架名],[自定义类型回调],[debug标志])//初始化模块
//函数 obj@send 建议与$.post等同联系
//参数1:指向框架 等同于$.post里面第一个参数url一个道理
//参数2:数据类型 模块提供function,result,PONG 三种类型,其中result与PONG是模块占用,用户请勿填入,如果需要自定义其他类型,请在参数四定义回调函数。
//参数3:传送的数据
//参数4:回调函数
chat.send([指向框架],[数据类型],[数据],[回调函数])
//函数 obj@send@error 假如发送给某个框架,超出【超时时间范围内】,则运行回调函数.
//参数1:回调函数
//参数2:超时时间 超时时间单位为ms,默认为5000ms,如果填入0,则没有意义,如果填如果负数,则为默认值
//注意:这个error函数生效必须前提条件是在send里面的回调函数有效!如果send里面没有回调函数,则error不会生效。
chat.send().error([回调函数],[超时时间])
chat.close()//关闭mchat模块
下 面 的 例 子 通 用 这 个 地 方 的 网 页 模 板 \color{#FF0000}{下面的例子通用这个地方的网页模板} 下面的例子通用这个地方的网页模板
主页面:index.html
<html>
<head>
<script src="http://bgcls.gitee.io/webdata/messager.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<iframe src="iframe.html"></iframe>
</body>
<script>
window.onload = function(){
//写入下面在 主页面中的 代码
}
</script>
</html>
iframe: iframe.html
<html>
<head>
<script src="http://bgcls.gitee.io/webdata/messager.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<a>这是子页面</a>
</body>
<script>
window.onload = function(){
//写入下面在 iframe中的 代码
}
</script>
</html>
使用主页面的变量例子
在主页面中:
window.test="test";
chat=mchat("host");
在iframe中:
//调用父页面的变量例子
chat=mchat("test1");
chat.send("host","function","window.test",function(data){console.log(data);});
使用主页面的函数
在主页面中:
chat=mchat("host");
function a1(a){
return a+1;
}
在iframe中:
//调用父页面的函数例子
chat=mchat("test2");
chat.send("host","function",["a1",100],function(data){console.log(data);});
主页面向iframe发送消息的例子
在主页面中:
<button οnclick="sendtest()"></button>
window.test="test";
chat=mchat("host");
function sendtest(){
chat.send("test3","message","test");
}
在iframe中:
//接收父页面传过来的消息例子
fn=function(data){console.log(data)}
chat=mchat("test3",fn);/*自定义消息类型例子*/
主页面callback消息处理
在主页面中:
callback=function(data){
return data["args"][0]+100;
}
chat=mchat("host",callback);
在iframe中:
chat=mchat("test1");
chat.send("host","message",50,function(data){alert("计算结果"+data)})
callback 多参传递
在主页面中:
callback=function(data){
var result=[];
for(var i in data["args"]){
result[i]+="this is "+result[i];
}
return result;
}
chat=mchat("host",callback);
在iframe中:
chat=mchat("test1");
chat.send("host","message",["a","b","c","d"],function(data){
alert("计算结果:"+JSON.stringify(data));
})
增加超时回调函数
在主页面中:
chat=mchat("host");
//发送给已经定义了的框架
chat.send("test1","function","1+1",function(data){alert("计算结果"+data)}).error(function(){alert("test1访问超时");},5000);
//发送给一个没有定义的iframe框架
chat.send("test2","function","1+1",function(data){alert("计算结果"+data)}).error(function(){alert("test2访问超时");},5000);
在iframe中:
chat=mchat("test1");
完整代码,请下载下面的例子来看