サーチ…
構文
-
windowObject.postMessage(message, targetOrigin, [transfer]); -
window.addEventListener("message", receiveMessage);
パラメーター
| パラメーター | |
|---|---|
| メッセージ | |
| targetOrigin | |
| 転送 | optional |
入門
.postMessage()とは何か、いつ、なぜそれを使うのですか?
.postMessage()メソッドは、クロスオリジンスクリプト間の通信を安全に許可する方法です。
通常、2つの異なるページは、たとえそれらのうちの1つが別のiframes ( iframes )に埋め込まれていたり、別のページが別のページ(たとえばwindow.open()など)から開かれていても、 window.open() )。 .postMessage() 、安全のままでこの制限を回避できます。
両方のページのJavaScriptコードにアクセスできる場合にのみ.postMessage()使用できます。受信者は送信者を検証し、それに応じてメッセージを処理する必要があるため、このメソッドを使用してアクセス権を持つ2つのスクリプト間で通信することができます。
子ウィンドウにメッセージを送信し、そのメッセージを子ウィンドウに表示する例を作成します。この例では、親/送信者ページはhttp://sender.comあり、子/受信者ページはhttp://receiver.comとみなされます。
メッセージを送信する
別のウィンドウにメッセージを送信するには、 windowオブジェクトへの参照が必要です。 window.open()は、新しく開いたウィンドウの参照オブジェクトを返します。ウィンドウオブジェクトへの参照を取得する他のメソッドについては、 otherWindowパラメータhereの説明を参照してください 。
var childWindow = window.open("http://receiver.com", "_blank");
子ウィンドウにメッセージを送信するために使用されるtextareaとsend buttonを追加します。
<textarea id="text"></textarea>
<button id="btn">Send Message</button>
buttonをクリックすると.postMessage(message, targetOrigin)を使用して.postMessage(message, targetOrigin)のtextareaを送信します。
var btn = document.getElementById("btn"),
text = document.getElementById("text");
btn.addEventListener("click", function () {
sendMessage(text.value);
text.value = "";
});
function sendMessage(message) {
if (!message || !message.length) return;
childWindow.postMessage(JSON.stringify({
message: message,
time: new Date()
}), 'http://receiver.com');
}
単純な文字列の代わりにJSONオブジェクトを送受信するためには、 JSON.stringify() JSON.parse()メソッドとJSON.parse()メソッドを使用できます。 Transfarable Objectは、 .postMessage(message, targetOrigin, transfer)メソッドの3番目のオプションパラメータとして指定できますが、現代のブラウザでもブラウザサポートはまだ不足しています。
この例では、受信者がhttp://receiver.comページであると想定されているため、urlをtargetOriginとして入力します。このパラメータの値は、送信するメッセージのchildWindowオブジェクトのoriginと一致する必要があります。 wildcardとして*を使用することは可能ですが、 wildcardを使用しないようにし、 セキュリティ上の理由から常にこのパラメーターを受信者固有の発信元に設定することを強く推奨します。
メッセージの受信、検証、および処理
この部分のコードは、受信者ページ(この例ではhttp://receiver.comてください。
メッセージを受信するには、 window message eventを聴く必要がありwindow 。
window.addEventListener("message", receiveMessage);
メッセージが受信されると、できるだけセキュリティを確保するために必要なステップがいくつかあります 。
- 送信者を検証する
- メッセージを検証する
- メッセージを処理する
送信者は、メッセージが信頼できる送信者から受信されたことを確認するために常に検証されるべきです。その後、悪意のあるものが何も受信されないように、メッセージ自体を検証する必要があります。これら2つの検証の後、メッセージを処理することができます。
function receiveMessage(ev) {
//Check event.origin to see if it is a trusted sender.
//If you have a reference to the sender, validate event.source
//We only want to receive messages from http://sender.com, our trusted sender page.
if (ev.origin !== "http://sender.com" || ev.source !== window.opener)
return;
//Validate the message
//We want to make sure it's a valid json object and it does not contain anything malicious
var data;
try {
data = JSON.parse(ev.data);
//data.message = cleanseText(data.message)
} catch (ex) {
return;
}
//Do whatever you want with the received message
//We want to append the message into our #console div
var p = document.createElement("p");
p.innerText = (new Date(data.time)).toLocaleTimeString() + " | " + data.message;
document.getElementById("console").appendChild(p);
}