コーディングを行うと、次のようなクロスドメインの状況に遭遇することがよくあります。
1. ページ内での iframe のネストと iframe を使用したメッセージング
2. ページ間および複数のページ間でメッセージを転送する
これらの厄介なクロスドメインの問題に対応して、HTML5 は特別に新機能 postMessage (クロスドキュメント メッセージ送信) を開始しました。 postMessage を使用する場合は、data とoriginUrl の 2 つのパラメーターを渡す必要があります。データは渡す必要があるコンテンツを指しますが、一部のブラウザーは文字列パラメータのみを処理できるため、通常はデータをシリアル化(つまり JSON.stringify() します)し、originUrl はターゲット URL と指定されたウィンドウを指します。
以下に例を示します。誰でも理解しやすく、書きやすいと思います。
1. ページ内のネストされた iframe
親ページ:
html:
<div id='parent'>こんにちは言葉 postMessage</div><iframe src=http://127.0.0.1:8082/index2.html id='child'></iframe>
js:
window.onload=function(){ window.frames[0].postMessage('postMessage','http://127.0.0.1:8082/index2.html')} window.addEventListener('message',function(e) { console.log(e) document.getElementById('parent').style.color=e.data})サブページ:
html:
<div id='button' onclick='changeColor();' style=color: yellow>情報を受け入れる</div>
js:
window.addEventListener('message',function(e){ console.log(e) let color = document.getElementById('button').style.color window.parent.postMessage(color,'http://127.0.0.1 :8081/index.html')});function changeColor(){ let buttonColor = document.getElementById('button').style.color buttonColor='#f00' window.parent.postMessage(buttonColor,'http://127.0.0.1:8081/index.html')}親ページは、postMessage メソッドを通じてメッセージを iframe に渡し、子ページは window.addEventListener を通じてメッセージ メソッドをリッスンして、親ページから渡された値を取得します。以下の図に示すように、データは親ページによって渡される値です。
子ページが親ページにメッセージを送信するとき、window.parent.postMessage(data,url) を通じて値を渡すのではなく、postMessage メソッドを通じてメッセージも渡します。親ページは、値を取得するときにメッセージ イベントもリッスンします。
2. 複数のページ間でメッセージを渡す
親ページ:
html:
<div id='parent' onclick=postMessage()>こんにちはポストメッセージ</div>
js:
letparent = document.getElementById('parent')function postMessage(){ let windowOpen=window.open('http://127.0.0.1:8082/index2.html','postMessage') setTimeout(function(){ windowOpen .postMessage('postMessageData','http://127.0.0.1:8082/index2.html') },1000) }サブページ:
html:
<div id='button' onclick='changeColor();' style=color:#f00>情報を受け入れる</div>
js:
window.addEventListener('メッセージ',function(e){ console.log(e) });親ページは、window.open を通じて別のページを開くように子ページにメッセージを送信し、値を子ページに渡します。 postMessage を使用して値を転送する場合、setTimeout を使用してメッセージの配信を遅らせる必要があることに注意してください。これは、サブページの読み込みが一度に完了しないためです。これは、サブページの listen イベントが完了しないことを意味します。はまだ開始されていないため、この時点では値は渡されません。
以上がこの記事の全内容です。皆様の学習のお役に立てれば幸いです。また、VeVb Wulin Network をご支援いただければ幸いです。