與訊息進行安全的跨域通訊
window.postMessage() 方法及其相對事件處理程式 window.onmessage 可以安全地用於啟用跨源通訊。
可以呼叫目標 window 的 postMessage() 方法向另一個 window 傳送訊息,window 將能夠使用其 onmessage 事件處理程式攔截它,詳細說明它,並且如果需要,再次使用 postMessage() 將響應傳送回傳送方視窗。
視窗與子框架通訊的示例
-
http://main-site.com/index.html的內容:<!-- ... --> <iframe id="frame-id" src="http://other-site.com/index.html"></iframe> <script src="main_site_script.js"></script> <!-- ... --> -
http://other-site.com/index.html的內容:<!-- ... --> <script src="other_site_script.js"></src> <!-- ... --> -
main_site_script.js的內容:// Get the <iframe>'s window var frameWindow = document.getElementById('frame-id').contentWindow; // Add a listener for a response window.addEventListener('message', function(evt) { // IMPORTANT: Check the origin of the data! if (event.origin.indexOf('http://other-site.com') == 0) { // Check the response console.log(evt.data); /* ... */ } }); // Send a message to the frame's window frameWindow.postMessage(/* any obj or var */, '*'); -
other_site_script.js的內容:window.addEventListener('message', function(evt) { // IMPORTANT: Check the origin of the data! if (event.origin.indexOf('http://main-site.com') == 0) { // Read and elaborate the received data console.log(evt.data); /* ... */ // Send a response back to the main window window.parent.postMessage(/* any obj or var */, '*'); } });