postMessage

postMessage メソッド (DOM)

[2] postMessage メソッドは、 Web におけるプロセス間通信のためのメソッドです。

仕様書

文脈

[112] Window オブジェクトMessagePort オブジェクトDedicatedWorkerGlobalScope オブジェクトWorker オブジェクトBroadcastChannel オブジェクトに存在します。

[159] SharedWorker オブジェクトには存在しませんが、 かわりに port IDL属性があって、 MessagePort オブジェクトにアクセスできます。

引数

[160] 第1引数は送信するデータです。 postMessage メソッドではこれを 「メッセージ」と呼んでいます。 メッセージとしては任意の JavaScript値を指定できます。

[176] ただし、送信されるのは指定された値そのものではなく、 構造化クローンです。


[161] 第2引数以後は文脈オブジェクトによって異なります。 元は引数をいくつか順に指定する形式でしたが、 2018年の改訂以後省略可能な辞書 PostMessageOptions 形式の引数 >>18 で指定できるようになりました >>22

Window オブジェクトの場合

[25] 第2引数 USVString または辞書引数 WindowPostMessageOptions (PostMessageOptions継承 >>18) の省略可能な USVString の値 targetOrigin >>18 には、投函先の起源を指定します。投函先が実際には異なる起源なら、 メッセージは無視されます (エラーにもなりません)。

[26] 起源は、次のいずれかの値を指定できます。

[29] 相対URLは指定できません。

[30] 例えば https://hoge.example/foo/bar を指定すると、 https://hoge.example 下の任意の文書などが受信できます。

[31] 第3引数または辞書引数 PostMessageOptions の省略可能な値 transfer >>18 には、 Transferable配列を指定できます。 該当するものがなければ、省略できます。

MessagePortDedicatedWorkerGlobalScopeWorker の場合

[114] 第2引数または辞書引数 PostMessageOptions の省略可能な値 transfer >>18 には、 Transferable配列を指定できます。 該当するものがなければ、省略できます。

BroadcastChannel オブジェクトの場合

[139] 第1引数のみです。

処理

Window の場合

[21] Window インターフェイスpostMessage メソッドは、 window post message steps、 すなわち次のようにしなければなりません >>18

  1. [177] 引数群を必須の any、 必須の USVString、 省略可能な sequence<object> か、 必須の any、 省略可能な WindowPostMessageOptions のいずれかとして解釈します。
    1. [96] メッセージを、第1引数を any として解釈した結果に設定します。
    2. [178] 前者の場合、
      1. [97] 対象起源を、第2引数を USVString として解釈した結果に設定します。
      2. [98] transfer を、第3引数を sequence<object> として解釈した結果に設定します。 既定値は、空リストとします。
    3. [113] 後者の場合、
      1. [179] オプション群を、第2引数を WindowPostMessageOptions と解釈した結果に設定します。
      2. [180] 対象起源を、 オプション群targetOrigin に設定します。
      3. [181] transferを、 オプション群transfer に設定します。
  2. [106] 対象窓を、文脈オブジェクトに設定します。
  3. [108] 対象Realm を、対象窓Realmに設定します。
  4. [83] 現職設定群を、現職設定群オブジェクトに設定します。
  5. [109] 対象起源により、
    *
    対象起源はそのまま * とします。
    /
    対象起源を、現職設定群起源に設定します。
    それ以外
    1. [100] URL を、対象起源URL構文解析器を適用した結果に設定します。
    2. [101] URL失敗の場合、
      1. [102] SyntaxError DOMException投げ、 ここで停止します。
    3. [103] 対象起源を、URL起源に設定します。
  6. [99] 直列化結果を、 メッセージtransferStructuredSerializeWithTransfer を適用した結果に設定します。 例外投げられれば、再び投げ、ここで停止します。
  7. [130] タスクをキューに追加します。
    タスク源
    対象窓関連エージェントイベントループ投稿済みメッセージタスク源
    処理
    1. [82] 対象起源* 以外で、 対象窓文書起源対象起源同じ起源ければ、
      1. [93] ここで停止します。
    2. [81] 起源を、現職設定群起源直列化に設定します。
    3. [104] 始点を、現職設定群大域オブジェクトWindowProxy に設定します。
    4. [110] 記録を、直列化結果対象Realmについて StructuredDeserializeWithTransfer した結果に設定します。 例外投げられた場合、
      1. [131] イベントを発火します。
        対象
        対象窓
        messageerror
        インターフェイス
        MessageEvent
        origin
        起源
        source
        始点
      2. [132] ここで停止します。
    5. [91] イベントを発火します。
      対象
      対象窓
      message
      インターフェイス
      MessageEvent
      origin
      起源
      source
      始点
      data
      記録Deserialized
      ports
      記録TransferredValuesMessagePort をすべて同じ順に含めた凍結配列

[33] 送信したメッセージは、 Windowmessage イベントとして受信することができます。

message を参照。

MessagePortDedicatedWorkerGlobalScopeWorker の場合

[115] MessagePort オブジェクトWorker オブジェクトDedicatedWorkerGlobalScope オブジェクトpostMessage は、 message port post message options、 すなわち次のようにしなければなりません >>111, >>156, >>158

  1. [157] ポートを、文脈オブジェクトにより、次の値に設定します。
    MessagePort
    文脈オブジェクト
    DedicatedWorkerGlobalScope
    文脈オブジェクト暗示的ポート
    Worker
    文脈オブジェクト暗示的ポート
  2. [116] メッセージを、必須の第1引数を any として解釈した結果に設定します。
  3. [117] オプション群を、省略可能な第2引数をオブジェクト配列または MessagePortOptions として解釈した結果に設定します。
  4. [182] オプション群MessagePortOptions の場合、
    1. [183] transfer を、 オプション群transfer に設定します。
  5. [184] それ以外の場合、
    1. [185] transfer を、 オプション群に設定します。
  6. [120] transferポートが含まれる場合、
    1. [121] DataCloneError投げ、ここで停止します。
  7. [118] 対象ポートを、ポートentangle されているポートに設定します。
  8. [122] 対象ポートnull 以外で、 transfer対象ポートが含まれるなら、
    1. [123] doomed を、に設定します。
    2. [124] 開発者コンソールに、 通信路が失われることを報告しても構いません。
  9. [126] それ以外の場合、
    1. [119] doomed を、に設定します。
  10. [163] 結果を、 StructuredSerializeWithTransfer (メッセージtransfer) の結果に設定します。例外投げられたら、再び投げ、ここで停止します。
  11. [133] 対象ポートnull 以外で、 doomedなら、
    1. [142] 結果についての処理 (>>125) を対象ポートポートメッセージキューに追加します。

[125] 結果についての処理は、次のようなものです >>111。 ここで、最終対象ポートは、実行側で指定される変数です (ポートメッセージキューに追加参照)。

  1. [85] Realmを、最終対象ポート関連Realmに設定します。
  2. [165] 記録を、 StructuredDeserializeWithTransfer (結果, Realm) の結果に設定します。 例外投げられた場合、
    1. [92] イベントを発火します。
      インターフェイス
      MessageEvent
      対象
      最終対象ポート
      messageerror
    2. [105] ここで停止します。
  3. [168] イベントを発火します。
    インターフェイス
    MessageEvent
    対象
    最終対象ポート
    message
    data
    記録Deserialized
    ports
    記録TransferredValues 内の各 MessagePort を同じ順序で含めた凍結済み配列

BroadcastChannel オブジェクトの場合

[140] BroadcastChannel オブジェクトpostMessage は、 次のようにしなければなりません >>138

  1. [141] メッセージを、必須の第1引数を any として解釈した結果に設定します。
  2. [143] 始点を、文脈オブジェクトに設定します。
  3. [145] 始点閉じ済みフラグなら、
    1. [146] InvalidStateError投げ、ここで停止します。
  4. [144] 始点設定群を、始点BroadcastChannel設定群オブジェクトに設定します。
  5. [147] 始点通信路を、始点通信路名に設定します。
  6. [149] 複製メッセージを、StructuredSerialize(メッセージ対象Realm) の結果に設定します。 例外投げられれば、再び投げ、ここで停止します。
  7. [150] 終点群を、始点設定群始点通信路BroadcastChannelすべてのリストに設定します。
  8. [151] 終点群から、始点を除去します。
  9. [152] 終点群の各項目終点について、順に、
    1. [153] タスクをキューに追加します。
      処理
      1. [154] 対象Realmを、終点関連設定群オブジェクトRealmに設定します。
      2. [136] 起源を、始点設定群起源直列化に設定します。
      3. [127] データを、 StructuredDeserialize (複製メッセージ, 対象Realm) の結果に設定します。 例外投げられた場合、
        1. [134] イベントを発火します。
          インターフェイス
          MessageEvent
          messageerror
          対象
          終点
          origin
          起源
        2. [135] ここで停止します。
      4. [155] イベントを発火します。
        インターフェイス
        MessageEvent
        message
        対象
        終点
        origin
        起源
        data
        データ
      タスク源
      終点関連エージェントイベントループDOM操作タスク源
      タスク文書
      終点関連エージェントイベントループ窓イベントループの場合、 終点BoardcastChannel設定群オブジェクト有責文書
[128] メッセージポート等を送ることはできません。 BroadcastMessage でできないことをするには、共有ワーカーを作って中継する必要があります。

歴史

登場

[14] 最初 Web Applications 1.0 に追加された時は Document オブジェクトに属していました。

[15] しかし同一起源ポリシーに関する検査が複雑になるとして、より「外側」 である Window オブジェクトへと移動されました。

[16] Opera ははじめに Document オブジェクトに実装しましたが、 後に Window オブジェクトに移動しました。 他のWebブラウザーははじめから Window オブジェクトに実装しました。

[17] postMessageHTML5 の新機能の中では最も早期に実装されたものの一つでした。

実装開始

[1] Cross-document messaging in Opera - Arve Bersvendsen http://virtuelvis.com/archives/2005/12/cross-document-messaging

[50] Opera 8 β にはありませんでしたが、 Opera 8.5 では実装されていました。

[3] The cross-document messaging APIs (Ian Hickson <ian@...> 著, 2007-08-09 00:51:36 +09:00 版) http://permalink.gmane.org/gmane.org.w3c.whatwg.discuss/11634

[4] Index of /specs/dom/messages (2008-02-13 01:58:34 +09:00 版) http://www.hixie.ch/specs/dom/messages/

[23] Fixed a security problem with postMessage() (Ian Hickson <ian@...> 著, 2008-02-12 20:03:46 +09:00 版) http://permalink.gmane.org/gmane.org.w3c.whatwg.discuss/13237 (名無しさん)

[24] IE Team Feedback on HTML 5.0 Cross Document Messaging (Sunava Dutta <sunavad@...> 著, 2008-02-22 03:18:40 +09:00 版) http://permalink.gmane.org/gmane.org.w3c.whatwg.discuss/13320

[32] postMessage() issues (Ian Hickson <ian@...> 著, 2008-04-16 00:10:07 +09:00 版) http://permalink.gmane.org/gmane.org.w3c.whatwg.discuss/13716

[38] postMessage feedback (Ian Hickson <ian@...> 著, 2008-04-24 23:49:56 +09:00 版) http://permalink.gmane.org/gmane.org.w3c.whatwg.discuss/13867

[39] (X)HTML5 Tracking ( 版) http://html5.org/tools/web-apps-tracker?from=4547&to=4548

[40] HTML5 Communications ( 版) http://dev.w3.org/html5/postmsg/Overview.html

[41] IRC logs: freenode / #whatwg / 20100212 ( 版) http://krijnhoetmer.nl/irc-logs/whatwg/20100212#l-271

[42] David Baron's weblog: setTimeout with a shorter delay ( 版) http://dbaron.org/log/20100309-faster-timeouts

[43] [whatwg] postMessage's target origin argument can be a full URL in some implementations ( 版) http://lists.whatwg.org/pipermail/whatwg-whatwg.org/2010-August/027848.html

[44] HTML5 Revision Tracker ( 版) http://html5.org/tools/web-apps-tracker?from=5276&to=5277

[45] [whatwg] postMessage's target origin argument can be a full URL in some implementations ( ( 版)) http://lists.whatwg.org/htdig.cgi/whatwg-whatwg.org/2010-November/029037.html

[46] Web Applications 1.0 r5682 Revert r5277's removal of '/' as a magic value to postMessage(), since it has useful use cases. Paths in absolute URLs are still ignored without raising an exception. ( ( 版)) http://html5.org/tools/web-apps-tracker?from=5681&to=5682

[47] HTML5 Web Messaging ( ( 版)) http://www.w3.org/TR/2010/WD-webmessaging-20101118/

[48] IE で postMessage 的実装をちゃんとやる - 冬通りに消え行く制服ガールは、夢物語にリアルを求めない。 - subtech ( ( 版)) http://subtech.g.hatena.ne.jp/cho45/20101207/1291719344

[49] HTML5 Web Messaging ( ( 版)) http://www.w3.org/TR/2011/WD-webmessaging-20110317/

[65] Web Applications 1.0 r6690 Make postMessage() accept the second and third arguments in either order. Compat with WebKit and hopefully solves the difficulty people have about remembering which goes first. ( ( 版)) http://html5.org/tools/web-apps-tracker?from=6689&to=6690

[66] Web Applications 1.0 r6691 Revert last checkin. My testing was bogus. ( ( 版)) http://html5.org/tools/web-apps-tracker?from=6690&to=6691

[67] HTML5 Web Messaging ( ( 版)) http://www.w3.org/TR/2011/WD-webmessaging-20111020/

[68] IE 6/7 で文書間通信を実現するための一案: Days on the Moon ( ( 版)) http://nanto.asablo.jp/blog/2011/12/08/6237308

[69] HTML5 Web Messaging ( ( 版)) http://www.w3.org/TR/2012/WD-webmessaging-20120313/

[70] HTML5 Web Messaging ( ( 版)) http://www.w3.org/TR/2012/CR-webmessaging-20120501/

[71] Securing Frame Communication in Browsers ( ( 版)) http://seclab.stanford.edu/websec/frames/post-message.pdf

[72] Compound Document by Reference Framework 1.0 ( ( 版)) http://www.w3.org/TR/CDR/#event-propagation

[73] Interview with Ian Hickson, HTML editor | HTML5 Doctor ( ( 版)) http://html5doctor.com/interview-with-ian-hickson-html-editor/

[74] RemoteDocumentMessaging - WHATWG Wiki ( ( 版)) http://wiki.whatwg.org/wiki/RemoteDocumentMessaging

[75] IRC logs: freenode / #whatwg / 20130621 ( ( 版)) http://krijnhoetmer.nl/irc-logs/whatwg/20130621#l-585

[76] [whatwg] web messaging - postMessage ( ( 版)) http://lists.whatwg.org/pipermail/whatwg-whatwg.org/2013-September/040800.html

[77] Web Applications 1.0 r8247 The bulk of this is editorial: refactoring how scripts are defined so that all the common stuff is in a shared 'settings object' rather than being duplicated per script. But this also cleans up how postMessage() interacts with the event loop and a few other things I've since forgotten. ( ( 版)) http://html5.org/tools/web-apps-tracker?from=8246&to=8247

[78] Web Applications 1.0 r8741 Try to explain why postMessage()'s privacy implications aren't actually anything new ( ( 版)) http://html5.org/r/8741

[79] JavaScript - WebWorkersで巨大データ転送の不思議 - Qiita ( ( 版)) http://qiita.com/Quramy/items/8c12e6c3ad208c97c99a

[5] CfC: publish Proposed Recommendation of Web Messaging; deadline March 28 (Arthur Barstow 著, 版) https://lists.w3.org/Archives/Public/public-webapps/2015JanMar/0848.html

[6] Part2 - browsersec - Browser Security Handbook, part 2 - Browser Security Handbook - Google Project Hosting ( 版) https://code.google.com/p/browsersec/wiki/Part2#Gaps_in_DOM_access_control

[7] YuzuJS/setImmediate ( 版) https://github.com/YuzuJS/setImmediate

Note that Internet Explorer 8 includes a synchronous version of postMessage. We detect this, or any other such synchronous implementation, and fall back to another trick.

[8] HTML5 Web Messaging ( ( 版)) http://www.w3.org/TR/2015/PR-webmessaging-20150407/

[9] HTML5 Web Messaging ( ( 版)) http://www.w3.org/TR/2015/REC-webmessaging-20150519/

[10] Errata/WebMessaging - WEBAPPS ( 版) https://www.w3.org/2008/webapps/wiki/Errata/WebMessaging

[11] All Results ( 版) https://w3c.github.io/test-results/webmessaging/all

[12] HTML5 Web Messaging ( 版) http://www.w3.org/TR/2015/REC-webmessaging-20150519/

Open Bugs 27128

[13] HTML5 Web Messaging ( 版) http://www.w3.org/TR/2015/REC-webmessaging-20150519/

Open Bugs 18242

[34] PSA: Change the Latest Editor's Drafts of WebStorage, WebWorkers, WebMessaging, Server-Sent Events and WebSockets (Xiaoqian Wu 著, 版) https://lists.w3.org/Archives/Public/public-webapps/2015OctDec/0099.html

[35] Safari 4.0 ( 版) https://developer.apple.com/library/safari/releasenotes/General/WhatsNewInSafari/Articles/Safari_4_0.html#//apple_ref/doc/uid/TP40014305-CH4-SW13

WebKit now supports the HTML5 cross-document messaging standard, allowing documents served from different domains to communicate with each other directly without the need for server relaying.

[36] High-performance Web Worker messages | Read the Tea Leaves ( 版) http://nolanlawson.com/2016/02/29/high-performance-web-worker-messages/

My tests confirmed that stringifying is indeed faster than sending raw objects, and that the message size has a dramatic impact on the speed of worker communication.

Furthermore, the only real benefit comes if you stringify the entire message. Even a small object that wraps the stringified message (e.g. {msg: JSON.stringify(message)}) performs worse than the fully-stringified case. (These results differ between Chrome, Firefox, and Safari, but keep reading for the full analysis.)

[37] Write structured clone algorithm in terms of ECMAScript · whatwg/html@bfb960c ( 版) https://github.com/whatwg/html/commit/bfb960c938580c95e77365e614218b952f96375b

[80] Make window.postMessage grab settings objects before going async · whatwg/html@26f5645 ( 版) https://github.com/whatwg/html/commit/26f5645b0c161c60903e945adace86165d56c03c

[84] Use FrozenArray for Navigator#languages and MessageEvent#ports · whatwg/html@e4df68a ( 版) https://github.com/whatwg/html/commit/e4df68a41b86753c7fcdd0d8ea4615f63ffc87e9

[86] Clarify settings object, realm, and global relationships · whatwg/html@0866f1b ( 版) https://github.com/whatwg/html/commit/0866f1b3f4b4ea5a99a30909e9bbe557dea0b460

[87] Editorial: else -> false in postMessage() algorithm · whatwg/html@60e5fc3 ( 版) https://github.com/whatwg/html/commit/60e5fc361572c8d0ef576dc78542ec4b845aef5b

[88] postMessage should always be flexible; HT @NAndreasson · w3c/webappsec-cowl@7ec257b ( 版) https://github.com/w3c/webappsec-cowl/commit/7ec257b9951bff0fb8f81253b94124eb1afe64e4

[89] Use USVString for all URLs ( (domenic著, )) https://github.com/whatwg/html/commit/018b983b77b2cd908f6d00100e7e0abe893dd2c3

[90] Use only the incumbent global in postMessage (domenic著, ) https://github.com/whatwg/html/commit/8259a69aab7538b772beebad1ff69dca44b159ab

[95] Parse postMessage()'s targetOrigin argument (annevk著, ) https://github.com/whatwg/html/commit/8282fc8dd47891160859375d0eacfcd08f9bdec4

[107] Tidy up the various postMessage algorithms (domenic著, ) https://github.com/whatwg/html/commit/ee103bbdba81bdbb8eb8e1bf77e9565f6158c5be

[19] javascript - postMessage still broken on IE11? - Stack Overflow ( ()) http://stackoverflow.com/questions/21070553/postmessage-still-broken-on-ie11

[94] Set some MessageEvent's isTrusted attributes to true (domenic著, ) https://github.com/whatwg/html/commit/eecea4bf565a442e98c2ec98bf298d082d196282

[162] Breaking: refactor structured clone into serialize/deserialize (domenic著, ) https://github.com/whatwg/html/commit/97d644c97335956610a31e8ad98d1a388c063e84

[129] Define messageerror (annevk著, ) https://github.com/whatwg/html/commit/25a94f606e983534a863a0559d65bd29bb940a02

[137] The WHATWG Blog — HTML and shared memory () https://blog.whatwg.org/html-and-shared-memory

[148] Remove Unicode serialization of an origin (annevk著, ) https://github.com/whatwg/html/commit/59ebd9c094d9d532458a9ee61f307bf41bc70811

[164] No longer remove tasks for document.open() by annevk · Pull Request #3665 · whatwg/html () https://github.com/whatwg/html/pull/3665

[22] Add postMessage overrides that take options (dtapuska著, ) https://github.com/whatwg/html/commit/c501dd8ca54a10083c110e695e68f5347b3c1ba9

[167] Add Window.postMessage override that takes a dictionary · Issue #3799 · whatwg/html () https://github.com/whatwg/html/issues/3799

[169] Add postMessage override that provides WindowPostMessageOptions. by dtapuska · Pull Request #3800 · whatwg/html () https://github.com/whatwg/html/pull/3800

[166] Mark postMessage()'s dictionary argument optional (dtapuska著, ) https://github.com/whatwg/html/commit/e3f1cc890a3d6bedc46379f65853529e9de91dc1

[170] " void postMessage(any message, optional sequenc..." · Issue #4137 · whatwg/html () https://github.com/whatwg/html/issues/4137

[171] Move optional param to be on PostMessageOptions dictionary instead of transfer. by dtapuska · Pull Request #4138 · whatwg/html () https://github.com/whatwg/html/pull/4138

[172] Fix postMessage domintro link to go to the correct overload (saschanaz著, ) https://github.com/whatwg/html/commit/1b6288baa27dd9dd894f05c092a86101f305daeb

[173] Fix postMessage link by saschanaz · Pull Request #4135 · whatwg/html () https://github.com/whatwg/html/pull/4135

[174] Mark PostMessageOptions argument as optional on MessagePort (dtapuska著, ) https://github.com/whatwg/html/commit/88493eca9066b740c2d2fd579b7250eb1307a6a2

[175] Move optional field to be on dictionary instead of transfer. by dtapuska · Pull Request #4156 · whatwg/html () https://github.com/whatwg/html/pull/4156

[186] Memorandum of Understanding Between W3C and WHATWG () https://www.w3.org/2019/04/WHATWG-W3C-MOU.html

[187] Add API for postMessage with PostMessageOptions (dtapuska著, ) https://github.com/w3c/ServiceWorker/commit/3b3197431df710b2d60a69cdb94be6a63cc64f6d

[188] Make Client.postMessage to unloaded client not throw (#1293) (jungkees著, ) https://github.com/w3c/ServiceWorker/commit/86d941499aee42c701b1d6dfc8dab1eeda5ef526

[189] Make Client.postMessage to unloaded client not throw by jungkees · Pull Request #1293 · w3c/ServiceWorker () https://github.com/w3c/ServiceWorker/pull/1293

[190] Client.postMessage() throwing for unloaded client is problematic · Issue #1291 · w3c/ServiceWorker () https://github.com/w3c/ServiceWorker/issues/1291

[191] Use ASCII serialization for origins (#1151) (jungkees著, ) https://github.com/w3c/ServiceWorker/commit/a47c6d86c1436a4fff573d2a5da92b0e14891fa2

[192] Specify which event loop to use for posting messages by domenic · Pull Request #4917 · whatwg/html () https://github.com/whatwg/html/pull/4917

[193] 'Window post message steps' doesn't define which event loop is used for queuing a task · Issue #4653 · whatwg/html () https://github.com/whatwg/html/issues/4653

[194] Editorial: use responsible document a little less (annevk著, ) https://github.com/whatwg/html/commit/7ba98545162f90439d4ae478c3abacdb6c818c98

[195] Consider removing settings object's responsible document · Issue #4335 · whatwg/html () https://github.com/whatwg/html/issues/4335

[196] Editorial: use responsible document a little less by annevk · Pull Request #4394 · whatwg/html () https://github.com/whatwg/html/pull/4394

[197] Moving Worklets · Issue #5 · w3c/whatwg-coord () https://github.com/w3c/whatwg-coord/issues/5