HTML5 postMessage解決跨域、跨iframe視窗訊息傳遞
阿新 • • 發佈:2019-02-01
主頁面 接收訊息:
<#-- 頁頭 --> <#assign pageTitle><@spring.message "secure.video.sidebar.videograb"/></#assign> <#assign currentNav="video"> <#include "/secure/commons/header.ftl"> <#-- 匯入macros --> <#include "/commons/macros.ftl"> <div class="container-fluid"> <div class="row"> <#-- 左側欄 --> <#assign sidebarNav="videoGrab"> <#include "/secure/commons/sidebar-video.ftl"> <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <h3 class="page-header"><@spring.message "secure.video.sidebar.videograb"/></h3> <iframe src="http://grab.polyv.net/grab/login?userId=${userid!''}&ts=${ts!''}&sign=${sign!''}" id="grabvideo" frameborder="0" scrolling="no" width="100%" height="100%" ></iframe> </div> </div> </div> <script src="/assets/js/libs/jquery/jquery-1.11.1.min.js"></script> <script> $(function(){ //接收 子頁面的通訊資訊 window.addEventListener('message',function(e){ var height=e.data; console.log(height); $('#grabvideo').css("height",height+100); },false); }); </script> <#-- 頁尾 --> <#include "/secure/commons/footer.ftl">
iframe子頁面 傳送訊息: (將本頁面的body高度,傳送到父頁面)
<script src="/resources/js/jquery-1.7.2.js"></script> <script type="text/javascript"> $(".container").css({ 'margin-top' : '-55px', 'width' : '95%' }); //向polyv的父iframe頁面傳遞高度 $(function(){ var height=3000; height=$(document.body).height(); window.parent.postMessage(height,"*"); }); </script>
參考文件:
先是主頁面HTML程式碼
- <sectionid="wrapper">
- <header><h1>postMessage (跨域)</h1></header>
- <article>
- <form>
- <p>
-
<labelfor="message">給iframe發一個資訊:</label><inputtype="text"name="message"value="son"id
- <inputtype="submit"/>
- </p>
- </form>
- <h4>目標iframe傳來的資訊:</h4>
- <pid="test">暫無資訊</p>
- <iframeid="iframe"src="xiebiji.com/works/postmessage/iframe.html"></iframe>
- </article>
- </section>
然後是iframe的HTML程式碼
- <form>
- <p>
- <labelfor="message">給父視窗發個資訊:</label><inputtype="text"name="message"value="dad"id="message"/>
- <inputtype="submit"/>
- </p>
- </form>
- <pid="test">暫無資訊。</p>
然後是主頁面中的JS程式碼 [javascript] view plain copy
- var win = document.getElementById("iframe").contentWindow;
- document.querySelector('form').onsubmit=function(e){
- win.postMessage(document.getElementById("message").value,"*");
- if (e.preventDefault){
- e.preventDefault();
- }
- e.returnValue = false;
- }
關鍵程式碼就一句:win.postMessage(document.getElementById("message").value,"*");
postMessage是通訊物件的一個方法,所以向iframe通訊,就是iframe物件呼叫postMessage方法。postMessage有兩個引數,缺一不可。第一個引數是要傳遞的資料,第二個引數是允許通訊的域,“*”代表不對訪問的域進行判斷,可理解為允許所有域的通訊。
然後是iframe中的JS程式碼
[javascript] view plain copy- var parentwin = window.parent;
- window.onmessage=function(e){
- document.getElementById("test")。innerHTML = e.origin + "say:" + e.data;
- parentwin.postMessage('HI!你給我發了"<span>'+e.data+'"</span>。',"*");
- };