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做的測試,屬於跨域,正常情況下是無法傳值的

嘗試在父頁面的文本框中輸入一些東西看一下

這樣我們就可以正常傳值了,隨后根據需求進行處理就可以了
附上ie下測試效果:
相關介紹:
- onpropertychange事件是為了兼容一下ie11以下版本,如果不需要兼容,可以去掉
- 建議使用addEventListener方法來正式使用,好出嘛,就是你同時添加兩個oninput事件使用這種方法不會沖突,否則只能同時響應一個方法
- 其他的還不知道,如果有需要可以在評論區留言

