JS window.name跨域封装

本文介绍了一种使用 JavaScript 的 window.name 属性实现跨域数据传输的方法,并提供了一个具体的封装函数实例。此方法适用于一些特定场景下的轻量级跨域通信需求。

JS window.name 跨域封装

 

 1 function CrossDomainName(target, agent, callback, security) {
 2     if (typeof target !== 'string' || typeof agent !== 'string' || typeof callback !== 'function') {
 3         throw '参数错误';
 4     }
 5     this.state = 0;
 6     this.target = target;//目标路径
 7     this.agent = agent;//代理文件
 8     this.callback = callback || Function;//回调函数
 9     this.security = security || true;
10     this.iframe = document.createElement('iframe');
11     var self = this;
12     function onload() {
13         if (self.state === 1) {
14             var data = self.iframe.contentWindow.name;
15             self.callback.call(self.iframe, data);
16             if (self) {
17                 self.iframe.contentWindow.document.close();//关闭文档流
18                 self.iframe.contentWindow.close();//关闭Iframe
19                 document.body.removeChild(self.iframe);//移除Iframe
20             }
21         } else if (self.state === 0) {
22             self.state = 1;
23             self.iframe.contentWindow.location = self.agent;
24         }
25     }
26     if (document.attachEvent) {
27         this.iframe.attachEvent('onload', onload);
28     } else if (document.addEventListener) {
29         this.iframe.addEventListener('load', onload, false);
30     } else {
31         this.iframe.onload = onload;
32     }
33     this.iframe.src = this.target;
34     document.body.appendChild(this.iframe);
35 }
36 //调用
37 new CrossDomainName('http://www.kingwell.com/kingwell.html', 'http://name.b.com/adfas.html', function (data) {
38     alert(data);
39 });

 

转载于:https://www.cnblogs.com/kingwell/p/3241353.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值