js跨域传值,兼容ie8以上

js跨域传值,兼容ie8以上

事先说明,此方法并不支持ie8,如果想要支持ie8的话,需要用这种思路(来自微软):

if (window.addEventListener) { 
  window.addEventListener('message', function (e) { 
    if (e.domain == 'example.com') { 
      if (e.data == 'Hello World') { 
        e.source.postMessage('Hello'); 
      } else { 
        console.log(e.data); 
      } 
    } 
  }); 
} 
else { // IE8 or earlier 
  window.attachEvent('onmessage', function (e) { 
    if (e.domain == 'example.com') { 
      if (e.data == 'Hello World') { 
        e.source.postMessage('Hello'); 
      } else { 
        alert(e.data); 
      } 
    } 
  }); 
} 

这里为了保持代码简洁,就不详细介绍了,有需要的可以在下方留言我会解答的

不写是因为网上好多例子都没有几个能解决跨域问题的,更多的还都是复制粘贴吸引人气的那些人,更可气

我们要实现的目的是:父页面的文本框每次改变,都会将内容发送到子页面由子页面处理:

我们这里的处理方式是在控制台打印出来

好啦先上代码:

  • 新建2个html,a.html和b.html
  • 我是为了省事将a.html放到了webStorm下,而b.html放到了我的IDEA项目中

a.html

<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
          name="viewport">
    <meta content="ie=edge" http-equiv="X-UA-Compatible">
    <title>父页面</title>
</head>
<body>

<label for="test">父页面的文本框
    <input id="test"  onpropertychange="sendMsg()" oninput="sendMsg()" type="text">
</label>
<br>
<hr>

<iframe id="child" src="http://localhost/a"></iframe>

<script type="text/javascript">
    <!--将文字发送到子页面-->
    function sendMsg() {
        var test = document.getElementById("test");
        console.log("父页面给子页面发送了" + test.value);
        window.frames[0].postMessage(test.value, "http://localhost");
    }
</script>

</body>
</html>

b.html

<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
          name="viewport">
    <meta content="ie=edge" http-equiv="X-UA-Compatible">
    <title>子页面</title>
</head>
<body>
这里是子页面内容
其实子页面几乎什么也没有
<script type="text/javascript">
    window.onmessage = function (event) {
        console.log("子页面收到了" + event.data)
    };
</script>
</body>
</html>

如图所示:

这里使用的是127.0.0.1和localhost做的测试,属于跨域,正常情况下是无法传值的

1486077-20190122160157998-1215925848.png

尝试在父页面的文本框中输入一些东西看一下

1486077-20190122160246438-226124549.png

这样我们就可以正常传值了,随后根据需求进行处理就可以了

附上ie下测试效果:
1486077-20190122160259975-448555911.png

相关介绍:

  • onpropertychange事件是为了兼容一下ie11以下版本,如果不需要兼容,可以去掉
  • 建议使用addEventListener方法来正式使用,好出嘛,就是你同时添加两个oninput事件使用这种方法不会冲突,否则只能同时响应一个方法
  • 其他的还不知道,如果有需要可以在评论区留言
posted on 2019-01-22 16:05 凉云 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/liangyun/p/10304375.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值