window.postMessage
window.postMessage()方法可以安全地实现跨域通信。
何为跨域?
同源:如果两个URL的协议(protocol,如ftp、http)、主机(host,如blog.csdn.net)、端口号(port,如80、5500)三者都相同,那么这两个URL是同源。否则两者的通信需要跨域。
值得注意的是,域(domain)、源(origin)两者不是一回儿事,比如
https://blog.csdn.net
,其域document.domain
为csdn.net
,而其源之主机window.location.host
为blog.csdn.net
。
1.用法
发送消息的页面:
- 1
接收消息的页面
- 1
- 2
- 3
- 4
window.addEventListener("message", function(e) {})
等效于
window.onmessage = function(e) {}
2.应用
发送消息的页面
file:///Users/xxx/xxx/daily/postMessage/postMessage.html
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
接受消息的页面
http://127.0.0.1:5500/daily/postMessage/onMessage.html
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
关于
window.opener
:返回打开当前窗口的那个窗口的引用,例如:在 window A 中打开了 window B,B.opener 返回 A.