js跨域传值,兼容ie8以上

时间:2022-10-24 15:51:32

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做的测试,属于跨域,正常情况下是无法传值的

js跨域传值,兼容ie8以上

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

js跨域传值,兼容ie8以上

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

附上ie下测试效果:

js跨域传值,兼容ie8以上

相关介绍:

  • onpropertychange事件是为了兼容一下ie11以下版本,如果不需要兼容,可以去掉
  • 建议使用addEventListener方法来正式使用,好出嘛,就是你同时添加两个oninput事件使用这种方法不会冲突,否则只能同时响应一个方法
  • 其他的还不知道,如果有需要可以在评论区留言