Postmessage to parent windows

Window.postMessage()

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

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

Syntax

The dispatched event

В otherWindow отправляемые сообщения могут быть обработаны следующим способом:

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

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

Читайте также:  Таблица сравнения всех windows

Вопросы безопасности

Если вы не ожидаете получения сообщения от других сайтов, не добавляйте обработчики событий message . Это гарантированный способ избежать проблем с безопасностью.

Если же вы хотите получать сообщения от других сайтов, то всегда необходимо идентифицировать отправителя, используя origin и возможно source свойства. Любой сайт (включая, например, http://evil.example.com ) может отправлять сообщения любым другим, и у вас нет гарантии, что неизвестный отправитель не пошлёт вредоносные сообщения. Однако даже если отправитель известен, вам всё равно необходимо всегда подтверждать синтаксис получаемого сообщения. Иначе, дыра в безопасности сайта, которому вы доверяете, может открыть дыру для межсайтового скриптинга на вашем сайте.

Всегда конкретизируйте целевой первоисточник, а не просто * , когда вы используете postMessage для отправки данных другим окнам. Вредоносный сайт может изменить локацию окна без вашего ведома и затем перехватить данные, посылаемые с использованием postMessage .

Example

Notes

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.

Читайте также:  Не удалось обновить windows 10 до версии 2004

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 Это API не было стандартизировано.

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.

Specifications

Specification Status Comment
HTML Living Standard
Определение ‘window.postMessage’ в этой спецификации.
Живой стандарт No change from Unknown
Unknown
Определение ‘window.postMessage’ в этой спецификации.
Неизвестно Initial definition.
Читайте также:  Как сделать img образ linux

Browser compatibility

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 1.0 (Да) 6.0 (6.0) [1]
8.0 (8.0) [2]
8.0 [3]
10.0 [4]
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 (en-US) and (en-US).

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

Оцените статью