window.postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.

Normally, scripts on different pages are allowed to access each other if and only if the pages they originate from share the same protocol, port number, and host (also known as the " same-origin policy "). window.postMessage() provides a controlled mechanism to securely circumvent this restriction (if used properly).

Broadly, one window may obtain a reference to another ( e.g., 凭借 targetWindow = window.opener ), and then dispatch a MessageEvent on it with targetWindow.postMessage() . The receiving window is then free to handle this event as needed. The arguments passed to window.postMessage() ( i.e., the “message”) are exposed to the receiving window through the event object .

句法

targetWindow.postMessage(message, targetOrigin, [transfer]);
					
targetWindow
A reference to the window that will receive the message. Methods for obtaining such a reference include:
message
Data to be sent to the other window. The data is serialized using the structured clone algorithm . This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself. [ 1 ]
targetOrigin
Specifies what the origin of targetWindow must be for the event to be dispatched, either as the literal string "*" (indicating no preference) or as a URI. If at the time the event is scheduled to be dispatched the scheme, hostname, or port of targetWindow 's document does not match that provided in targetOrigin , the event will not be dispatched; only if all three match will the event be dispatched. This mechanism provides control over where messages are sent; for example, if postMessage() was used to transmit a password, it would be absolutely critical that this argument be a URI whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party. Always provide a specific targetOrigin , not * , if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site.
transfer 可选
Is a sequence of Transferable objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.

The dispatched event

otherWindow can listen for dispatched messages by executing the following JavaScript:

window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
  if (event.origin !== "http://example.org:8080")
    return;
  // ...
}
					

The properties of the dispatched message are:

data

The object passed from the other window.

origin
origin of the window that sent the message at the time postMessage was called. This string is the concatenation of the protocol and "://", the host name if one exists, and ":" followed by a port number if a port is present and differs from the default port for the given protocol. Examples of typical origins are https://example.org (implying port 443 ), http://example.net (implying port 80 ),和 http://example.com:8080 . Note that this origin is not guaranteed to be the current or future origin of that window, which might have been navigated to a different location since postMessage 被调用。
source
A reference to the window object that sent the message; you can use this to establish two-way communication between two windows with different origins.

Security concerns

If you do not expect to receive messages from other sites, do not add any event listeners for message 事件。 This is a completely foolproof way to avoid security problems.

If you do expect to receive messages from other sites, always verify the sender's identity 使用 origin and possibly source properties. Any window (including, for example, http://evil.example.com ) can send a message to any other window, and you have no guarantees that an unknown sender will not send malicious messages. Having verified identity, however, you still should always verify the syntax of the received message . Otherwise, a security hole in the site you trusted to send only trusted messages could then open a cross-site scripting hole in your site.

Always specify an exact target origin, not * , when you use postMessage to send data to other windows. A malicious site can change the location of the window without your knowledge, and therefore it can intercept the data sent using postMessage .

Secure shared memory messaging

postMessage() throws when used with SharedArrayBuffer objects, you might need to make sure you cross-site isolated your site properly. Shared memory is gated behind two HTTP headers:

Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
					

To check if cross origin isolation has been successful, you can test against the crossOriginIsolated property available to window and worker contexts:

if (crossOriginIsolated) {
  // Post SharedArrayBuffer
} else {
  // Do something else
}
					

另请参阅 Planned changes to shared memory which is starting to roll out to browsers (Firefox 79, for example).

范例

/*
 * In window A's scripts, with A being on <http://example.com:8080>:
 */
var popup = window.open(/* popup details */);
// When the popup has fully loaded, if not blocked by a popup blocker:
// This does nothing, assuming the window hasn't changed its location.
popup.postMessage("The user is 'bob' and the password is 'secret'",
                  "https://secure.example.net");
// This will successfully queue a message to be sent to the popup, assuming
// the window hasn't changed its location.
popup.postMessage("hello there!", "http://example.com");
function receiveMessage(event)
{
  // Do we trust the sender of this message?  (might be
  // different from what we originally opened, for example).
  if (event.origin !== "http://example.com")
    return;
  // event.source is popup
  // event.data is "hi there yourself!  the secret response is: rheeeeet!"
}
window.addEventListener("message", receiveMessage, false);
					
/*
 * In the popup's scripts, running on <http://example.com>:
 */
// Called sometime after postMessage is called
function receiveMessage(event)
{
  // Do we trust the sender of this message?
  if (event.origin !== "http://example.com:8080")
    return;
  // event.source is window.opener
  // event.data is "hello there!"
  // Assuming you've verified the origin of the received message (which
  // you must do in any case), a convenient idiom for replying to a
  // message is to call postMessage on event.source and provide
  // event.origin as the targetOrigin.
  event.source.postMessage("hi there yourself!  the secret response " +
                           "is: rheeeeet!",
                           event.origin);
}
window.addEventListener("message", receiveMessage, false);
					

注意事项

Any window may access this method on any other window, at any time, regardless of the location of the document in the window, to send it a message. Consequently, any event listener used to receive messages must first check the identity of the sender of the message, using the origin and possibly source properties. This cannot be overstated: Failure to check the origin and possibly source properties enables cross-site scripting attacks.

As with any asynchronously-dispatched script (timeouts, user-generated events), it is not possible for the caller of postMessage to detect when an event handler listening for events sent by postMessage throws an exception.

postMessage() schedules the MessageEvent to be dispatched only after all pending execution contexts have finished . For example, if postMessage() is invoked in an event handler, that event handler will run to completion, as will any remaining handlers for that same event, before the MessageEvent is dispatched.

值对于 origin property of the dispatched event is not affected by the current value of document.domain in the calling window.

For IDN host names only, the value of the origin property is not consistently Unicode or punycode; for greatest compatibility check for both the IDN and punycode values when using this property if you expect messages from IDN sites. This value will eventually be consistently IDN, but for now you should handle both IDN and punycode forms.

值对于 origin property when the sending window contains a javascript: or data: URL is the origin of the script that loaded the URL.

Using window.postMessage in extensions

window.postMessage is available to JavaScript running in chrome code (e.g., in extensions and privileged code), but the source property of the dispatched event is always null as a security restriction. (The other properties have their expected values.)

It is not possible for content or web context scripts to specify a targetOrigin to communicate directly with an extension (either the background script or a content script). Web or content scripts can 使用 window.postMessage 采用 targetOrigin of "*" to broadcast to every listener, but this is discouraged, since an extension cannot be certain the origin of such messages, and other listeners (including those you do not control) can listen in.

Content scripts should use runtime.sendMessage to communicate with the background script. Web context scripts can use custom events to communicate with content scripts (with randomly generated event names, if needed, to prevent snooping from the guest page).

Lastly, posting a message to a page at a 文件: URL currently requires that the targetOrigin argument be "*" . file:// cannot be used as a security restriction; this restriction may be modified in the future.

规范

规范 状态 注释
HTML 实时标准
The definition of 'postMessage()' in that specification.
实时标准

浏览器兼容性

The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
postMessage Chrome 1 Edge 12 Firefox 8
8
Supports sending File and FileList objects between windows. This is only allowed if the recipient's principal is contained within the sender's principal for security reasons.
6
message parameter is serialized using the structured clone algorithm . This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself.
不支持 3 — 6
message parameter must be a string.
IE 10
10
IE10 had an important limitation: see this 文章 了解细节。
不支持 8 — 10
Support only for <frame> and <iframe> .
Opera 9.5 Safari 4 WebView Android 1 Chrome Android 18 Firefox Android 8
8
Supports sending File and FileList objects between windows. This is only allowed if the recipient's principal is contained within the sender's principal for security reasons.
6
message parameter is serialized using the structured clone algorithm . This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself.
不支持 4 — 6
message parameter must be a string.
Opera Android 10.1 Safari iOS 3.2 Samsung Internet Android 1.0
transfer argument Chrome ? Edge 12 Firefox 20 IE Yes Opera ? Safari ? WebView Android ? Chrome Android ? Firefox Android 20 Opera Android ? Safari iOS ? Samsung Internet Android ?

图例

完整支持

完整支持

兼容性未知 ?

兼容性未知

见实现注意事项。

另请参阅

元数据

  • 最后修改:
  1. Window
  2. 特性
    1. applicationCache
    2. caches
    3. closed
    4. console
    5. controllers
    6. crossOriginIsolated
    7. crypto
    8. customElements
    9. defaultStatus
    10. devicePixelRatio
    11. dialogArguments
    12. 目录
    13. document
    14. event
    15. frameElement
    16. frames
    17. fullScreen
    18. history
    19. indexedDB
    20. innerHeight
    21. innerWidth
    22. isSecureContext
    23. isSecureContext
    24. length
    25. localStorage
    26. location
    27. locationbar
    28. menubar
    29. mozAnimationStartTime
    30. mozInnerScreenX
    31. mozInnerScreenY
    32. mozPaintCount
    33. 名称
    34. navigator
    35. onabort
    36. onafterprint
    37. onanimationcancel
    38. onanimationend
    39. onanimationiteration
    40. onappinstalled
    41. onauxclick
    42. onbeforeinstallprompt
    43. onbeforeprint
    44. onbeforeunload
    45. onblur
    46. oncancel
    47. oncanplay
    48. oncanplaythrough
    49. onchange
    50. onclick
    51. onclose
    52. oncontextmenu
    53. oncuechange
    54. ondblclick
    55. ondevicelight
    56. ondevicemotion
    57. ondeviceorientation
    58. ondeviceorientationabsolute
    59. ondeviceproximity
    60. ondragdrop
    61. ondurationchange
    62. onended
    63. onerror
    64. onfocus
    65. onformdata
    66. ongamepadconnected
    67. ongamepaddisconnected
    68. ongotpointercapture
    69. onhashchange
    70. oninput
    71. oninvalid
    72. onkeydown
    73. onkeypress
    74. onkeyup
    75. onlanguagechange
    76. onload
    77. onloadeddata
    78. onloadedmetadata
    79. onloadend
    80. onloadstart
    81. onlostpointercapture
    82. onmessage
    83. onmessageerror
    84. onmousedown
    85. onmouseenter
    86. onmouseleave
    87. onmousemove
    88. onmouseout
    89. onmouseover
    90. onmouseup
    91. onmozbeforepaint
    92. onpaint
    93. onpause
    94. onplay
    95. onplaying
    96. onpointercancel
    97. onpointerdown
    98. onpointerenter
    99. onpointerleave
    100. onpointermove
    101. onpointerout
    102. onpointerover
    103. onpointerup
    104. onpopstate
    105. onrejectionhandled
    106. onreset
    107. onresize
    108. onscroll
    109. onselect
    110. onselectionchange
    111. onselectstart
    112. onstorage
    113. onsubmit
    114. ontouchcancel
    115. ontouchstart
    116. ontransitioncancel
    117. ontransitionend
    118. onunhandledrejection
    119. onunload
    120. onuserproximity
    121. onvrdisplayactivate
    122. onvrdisplayblur
    123. onvrdisplayconnect
    124. onvrdisplaydeactivate
    125. onvrdisplaydisconnect
    126. onvrdisplayfocus
    127. onvrdisplaypointerrestricted
    128. onvrdisplaypointerunrestricted
    129. onvrdisplaypresentchange
    130. onwheel
    131. opener
    132. origin
    133. outerHeight
    134. outerWidth
    135. pageXOffset
    136. pageYOffset
    137. parent
    138. 性能
    139. personalbar
    140. pkcs11
    141. screen
    142. screenLeft
    143. screenTop
    144. screenX
    145. screenY
    146. scrollbars
    147. scrollMaxX
    148. scrollMaxY
    149. scrollX
    150. scrollY
    151. self
    152. sessionStorage
    153. sidebar
    154. speechSynthesis
    155. status
    156. statusbar
    157. toolbar
    158. top
    159. visualViewport
    160. window
  3. 方法
    1. alert()
    2. atob()
    3. back()
    4. blur()
    5. btoa()
    6. cancelAnimationFrame()
    7. cancelIdleCallback()
    8. captureEvents()
    9. clearImmediate()
    10. clearInterval()
    11. clearTimeout()
    12. close()
    13. confirm()
    14. convertPointFromNodeToPage()
    15. convertPointFromPageToNode
    16. createImageBitmap()
    17. dump()
    18. fetch()
    19. find()
    20. focus()
    21. forward()
    22. getAttention()
    23. getComputedStyle()
    24. getDefaultComputedStyle()
    25. getSelection()
    26. home()
    27. matchMedia()
    28. minimize()
    29. moveBy()
    30. moveTo()
    31. open()
    32. openDialog()
    33. postMessage()
    34. print()
    35. prompt()
    36. queueMicrotask()
    37. releaseEvents()
    38. requestAnimationFrame()
    39. requestFileSystem()
    40. requestIdleCallback()
    41. resizeBy()
    42. resizeTo()
    43. restore()
    44. routeEvent()
    45. scroll()
    46. scrollBy()
    47. scrollByLines()
    48. scrollByPages()
    49. scrollTo()
    50. setCursor()
    51. setImmediate()
    52. setInterval()
    53. setTimeout()
    54. showModalDialog()
    55. sizeToContent()
    56. stop()
    57. updateCommands()
  4. 事件
    1. event
    2. afterprint
    3. animationcancel
    4. animationend
    5. animationiteration
    6. beforeprint
    7. beforeunload
    8. blur
    9. copy
    10. cut
    11. DOMContentLoaded
    12. error
    13. focus
    14. hashchange
    15. languagechange
    16. load
    17. message
    18. messageerror
    19. offline
    20. online
    21. orientationchange
    22. pagehide
    23. pageshow
    24. paste
    25. popstate
    26. rejectionhandled
    27. storage
    28. transitioncancel
    29. unhandledrejection
    30. unload
    31. vrdisplayconnect
    32. vrdisplaydisconnect
    33. vrdisplaypresentchange
  5. HTML DOM 相关页面
    1. BeforeUnloadEvent
    2. DOMStringMap
    3. ErrorEvent
    4. GlobalEventHandlers
    5. HTMLAnchorElement
    6. HTMLAreaElement
    7. HTMLAudioElement
    8. HTMLBRElement
    9. HTMLBaseElement
    10. HTMLBaseFontElement
    11. HTMLBodyElement
    12. HTMLButtonElement
    13. HTMLCanvasElement
    14. HTMLContentElement
    15. HTMLDListElement
    16. HTMLDataElement
    17. HTMLDataListElement
    18. HTMLDialogElement
    19. HTMLDivElement
    20. HTMLDocument
    21. HTMLElement
    22. HTMLEmbedElement
    23. HTMLFieldSetElement
    24. HTMLFormControlsCollection
    25. HTMLFormElement
    26. HTMLFrameSetElement
    27. HTMLHRElement
    28. HTMLHeadElement
    29. HTMLHeadingElement
    30. HTMLHtmlElement
    31. HTMLIFrameElement
    32. HTMLImageElement
    33. HTMLInputElement
    34. HTMLIsIndexElement
    35. HTMLKeygenElement
    36. HTMLLIElement
    37. HTMLLabelElement
    38. HTMLLegendElement
    39. HTMLLinkElement
    40. HTMLMapElement
    41. HTMLMediaElement
    42. HTMLMetaElement
    43. HTMLMeterElement
    44. HTMLModElement
    45. HTMLOListElement
    46. HTMLObjectElement
    47. HTMLOptGroupElement
    48. HTMLOptionElement
    49. HTMLOptionsCollection
    50. HTMLOutputElement
    51. HTMLParagraphElement
    52. HTMLParamElement
    53. HTMLPictureElement
    54. HTMLPreElement
    55. HTMLProgressElement
    56. HTMLQuoteElement
    57. HTMLScriptElement
    58. HTMLSelectElement
    59. HTMLShadowElement
    60. HTMLSourceElement
    61. HTMLSpanElement
    62. HTMLStyleElement
    63. HTMLTableCaptionElement
    64. HTMLTableCellElement
    65. HTMLTableColElement
    66. HTMLTableDataCellElement
    67. HTMLTableElement
    68. HTMLTableHeaderCellElement
    69. HTMLTableRowElement
    70. HTMLTableSectionElement
    71. HTMLTemplateElement
    72. HTMLTextAreaElement
    73. HTMLTimeElement
    74. HTMLTitleElement
    75. HTMLTrackElement
    76. HTMLUListElement
    77. HTMLUnknownElement
    78. HTMLVideoElement
    79. HashChangeEvent
    80. 历史
    81. ImageData
    82. 定位
    83. MessageChannel
    84. MessageEvent
    85. MessagePort
    86. Navigator
    87. NavigatorGeolocation
    88. NavigatorID
    89. NavigatorLanguage
    90. NavigatorOnLine
    91. NavigatorPlugins
    92. PageTransitionEvent
    93. Plugin
    94. PluginArray
    95. PopStateEvent
    96. PortCollection
    97. PromiseRejectionEvent
    98. RadioNodeList
    99. Transferable
    100. ValidityState
    101. WindowBase64
    102. WindowEventHandlers
    103. WindowTimers

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1