美文网首页
跨域消息传输window.postMessage()

跨域消息传输window.postMessage()

作者: lolivialucky | 来源:发表于2017-08-08 13:27 被阅读121次

该方法是HTML5用于跨域消息传输的API

发送窗口

window.postMessage()方法被调用时,会在所有页面脚本执行完毕之后(e.g., 在该方法之后设置的事件、之前设置的timeout 事件,etc.)向目标窗口派发一个 MessageEvent消息。 该MessageEvent消息有四个属性需要注意:
message 属性表示该message 的类型;
data 属性为 window.postMessage的第一个参数;
origin 属性表示调用window.postMessage()方法时调用页面的当前状态;
source 属性记录调用window.postMessage()方法的窗口信息。
语法

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

otherWindow:表示发送数据的窗口的window的引用,包括iframe的contentWindow属性和通过window.open打开的新窗口。
message表示要发送的数据,包扩字符串和对象(ie9以下不支持,可以利用字符串和json互换)。
origin表示接收窗口的域。

接收窗口

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

function receiveMessage(event)
{
  // For Chrome, the origin property is in the event.originalEvent
  // object.
  var origin = event.origin || event.originalEvent.origin; 
  if (origin !== "http://example.org:8080")
    return;

  // ...
}

回调函数接受一个事件对象event, event包含属性
data:接受的数据
origin:发送窗口的域
source:发送端的DOMWindow对象

相关文章

  • 跨域消息传输window.postMessage()

    该方法是HTML5用于跨域消息传输的API 发送窗口 window.postMessage()方法被调用时,会在所...

  • vuejs打开新窗口,窗口间通信

    [利用window.postMessage()实现跨域消息传递(JavaScript)] 功能描述:打开新窗口,关...

  • 2017.10.1

    1. 实现不同窗体间互相通信 (1) window.postMessage()支持跨文档消息传输(Cross ...

  • window.postMessage解决前端ajax跨域问题

    postMessage畅快解决跨域问题 本文主要是记录使用window.postMessage解决ajax跨域问题...

  • 跨域问题2

    使用window.postmessage方法来跨域 Html5里有一个属性window.postmessage也可...

  • JS跨域

    JS跨域--H5 postMessage window.postMessage是html5中新增了一个新的跨域方法...

  • 跨域【详解】

    本篇有四种方法跨域:CORS、JSONP、降域、window.postMessage() 1. CORS CORS...

  • JS跨域--H5 postMessage

    window.postMessage是html5中新增了一个新的跨域方法,可以用它向其他window对象发送消息,...

  • window.postMessage()实现iframe跨域消息

    event对象有三个属性,分别是origin,data和source。event.data表示接发送过来的数据。e...

  • iframe

    一、iframe跨域的几种常用方法 1、postmessage window.postMessage方法可以安全地...

网友评论

      本文标题:跨域消息传输window.postMessage()

      本文链接:https://www.haomeiwen.com/subject/gpqtrxtx.html