Skip to content

window.opener+postMessage 通讯 #87

Open
@dcharlie123

Description

@dcharlie123

window.opener

概述
返回打开当前窗口的那个窗口的引用,例如:在 window A 中打开了 window B,B.opener 返回 A.
如果当前窗口是由另一个窗口打开的,window.opener保留了那个窗口的引用。如果当前窗口不是由其他窗口打开的,则该属性返回 null.

postMessage

详细
可以安全地实现跨源通信。

语法

otherWindow.postMessage(message, targetOrigin, [transfer]);

otherWindow
其他窗口的一个引用,比如 iframe 的 contentWindow 属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames (en-US)
targetOrigin

通过窗口的 origin 属性来指定哪些窗口能接收到消息事件,其值可以是字符串"*"(表示无限制)或者一个 URI。在发送消息的时候,如果目标窗口的协议、主机地址或端口这三者的任意一项不匹配 targetOrigin 提供的值,那么消息就不会被发送;只有三者完全匹配,消息才会被发送。这个机制用来控制消息可以发送到哪些窗口;例如,当用 postMessage 传送密码时,这个参数就显得尤为重要,必须保证它的值与这条包含密码的信息的预期接受者的 origin 属性完全一致,来防止密码被恶意的第三方截获。如果你明确的知道消息应该发送到哪个窗口,那么请始终提供一个有确切值的 targetOrigin,而不是 *。不提供确切的目标将导致数据泄露到任何对数据感兴趣的恶意站点。

接收

window.addEventListener("message", receiveMessage, false);

message 的属性有:
data
从其他 window 中传递过来的对象。
origin
调用 postMessage 时消息发送方窗口的 origin . 这个字符串由 协议、“://“、域名、“ : 端口号”拼接而成。例如“https://example.org (隐含端口 443)”、“http://example.net (隐含端口 80)”、“http://example.com:8080”。请注意,这个 origin 不能保证是该窗口的当前或未来 origin,因为 postMessage 被调用后可能被导航到不同的位置。
source
对发送消息的窗口对象的引用; 您可以使用此来在具有不同 origin 的两个窗口之间建立双向通信。

使用

let target = window.open('http://localhost:8082')
window.addEventListener('message',function(evt){
  if(evt.origin==='http://localhost:8082'){
    target.postMessage({data:'hello world'},'http://localhost:8082')
  }
})
window.onload=function(){
  window.opener.postMessage('页面加载完成','http://localhost:8080')
}
window.addEventListener('message',function(evt){
  if(evt.origin==='http://localhost:8080'){
    console.log(evt.message)
  }
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions