20
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryを用いて、PostMessageで通信した時のイベントリスナを追加する

Posted at

クロスドメイン間の通信を行う時、便利なPostMessage

送信側は下記のように送信します。
messageに送りたいデータ、targetOriginには送信先のURLを引数とします。

window.postMessage(message, targetOrigin);

受信側ですが、
receiveMessageをイベントリスナに登録します。
これで、通信が行われた際、receiveMessageが呼び出されます。

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

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

これをjQueryに書き換えると

$(window).on("message", receiveMessage, false);

function receiveMessage(event)
{
  if (event.originalEvent.origin !== "http://example.org:8080")
    return;
}

ここで注意!

JavaScriptで書いた時のイベントオブジェクトのプロパティがEvent.originEvent以下にあります。

参考
window.postMessage
JQuery doesn't support postmessage event?

20
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?