Этот перевод не завершен. Пожалуйста, помогите перевести эту статью с английского

Window.postMessage() - этот метод позволяет безопасно отправлять кросдоменные запросы. Обычно сценариям на разных страницах разрешен доступ друг к другу только если страницы, которые их выполняли, передаются по одному  протоколу (обычно это https), номер порта (443 — по умолчанию для https) и хост (modulo Document.domain установленный страницами на одно и тоже значение). window.postMessage() предоставляет контролируемый механизм, чтобы обойти это ограничение способом, который безопасен при правильном использовании.

При вызове метода window.postMessage() он вызвает MessageEvent для отправки в целевом окне, когда завершается любой ожидающий сценарий, который должен быть выполнен (например, оставшиеся обработчики событий, если window.postMessage() вызвается из обработчика событий ранее заданных ожидающих таймаутов). MessageEvent имеет тип  messagedata-свойство которого устанавливает значение первого аргумента в методе window.postMessage(), свойство origin  соотвествует адресу основного документа в вызове window.postMessage во время  вызова window.postMessage(), свойство source указывает на окно, из которого window.postMessage() вызвали. (Другие стандартные свойства событий имеют ожидаемые значения)


otherWindow.postMessage(message, targetOrigin, [transfer]);
Ссылка на другое окно; такая ссылка может быть получена, к примеру, используя свойство contentWindow элемента iframe , объект возвращаемый, или по именновоному и числовому индексу Window.frames, если вы пытаетесь запустить сообщение из iframe в родительском окне, то родитель также является действительной ссылкой.
Данные, которые нужно отправить в другое окно. Данные сериализуются с использованием алгоритма структурированного клона. Это означает, что вы можете безопасно передавать большое количество объектов данных в окно назначения без необходимости их сериализации. [1]
Specifies what the origin of otherWindow 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 otherWindow'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 отправляемые сообщения могут быть прослушаны следующим способом:

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

function receiveMessage(event)
  if (event.origin !== "")

  // ...

Свойства отправляемых сообщений:

Объект переданный из другого окна.
The 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 (implying port 443), (implying port 80), and 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 was called.
Ссылка на объект window , который отправил сообщение; может быть использована для установки двустороннего соединения между окнами с разными origins.

Security concerns

If you do not expect to receive messages from other sites, do not add any event listeners for message events. 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 using the origin and possibly source properties. Any window (including, for example, 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.


 * In window A's scripts, with A being on <>:

var 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'",

// This will successfully queue a message to be sent to the popup, assuming
// the window hasn't changed its location.
popup.postMessage("hello there!", "");

function receiveMessage(event)
  // Do we trust the sender of this message?  (might be
  // different from what we originally opened, for example).
  if (event.origin !== "")

  // event.source is popup
  // is "hi there yourself!  the secret response is: rheeeeet!"
window.addEventListener("message", receiveMessage, false);
 * In the popup's scripts, running on <>:

// Called sometime after postMessage is called
function receiveMessage(event)
  // Do we trust the sender of this message?
  if (event.origin !== "")

  // event.source is window.opener
  // 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!",

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.

The value of the 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.

The value of the 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.) The targetOrigin argument for a message sent to a window located at a chrome: URL is currently misinterpreted such that the only value which will result in a message being sent is "*". Since this value is unsafe when the target window can be navigated elsewhere by a malicious site, it is recommended that postMessage not be used to communicate with chrome: pages for now; use a different method (such as a query string when the window is opened) to communicate with chrome windows. Lastly, posting a message to a page at a file: URL currently requires that the targetOrigin argument be "*". file:// cannot be used as a security restriction; this restriction may be modified in the future.


Specification Status Comment
HTML Living Standard
Определение 'window.postMessage' в этой спецификации.
Живой стандарт No change from Unknown
Определение 'window.postMessage' в этой спецификации.
Неизвестно Initial definition.

Browser compatibility

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 1.0 (Да) 6.0 (6.0)[1]
8.0 (8.0)[2]
9.5 4.0
transfer argument ? (Да) 20.0 (20.0) (Да) ? ?
Feature Android Edge Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support (Да) (Да) 6.0 (6.0)[1]
8.0 (8.0)[2]
(Да) (Да) (Да)
transfer argument ? ? 20.0 (20.0) Нет ? ?

[1] Prior to Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3), the message parameter must be a string. Starting in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3), the 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.

[2] Gecko 8.0 introduced support for 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.

[3] IE8 and IE9 only support it for <frame> and <iframe>.

[4] IE10 has important limitations: see this article for details.

See also