DIV CSS 佈局教程網

用jQuery與postMessage實現跨域iframe接口調用
編輯:JQuery特效代碼     

在實際開發中,父頁面常常需要調用嵌入其中的跨域 iframe 子頁面裡的公開方法,而同源策略又會阻擋直接的腳本訪問。借助 HTML5 提供的 postMessage 機制,再配合 jQuery 封裝一層簡潔的通信邏輯,就能優雅地實現父子頁面之間的雙向調用與回調。

核心通信腳本 cross.js

下面的封裝在 window 上掛載了一個 Cross 對象,通過 on 註冊接口、通過 call 發送消息,並利用 message 事件完成消息的分發與結果回傳:

(function(global){
  global.Cross = {
    signalHandler: {},
    on: function(signal, func){
      this.signalHandler[signal] = func;
    },
    call: function(win, domain, signal, data, callbackfunc){
      var notice = {"signal": signal, "data": data};
      if(!!callbackfunc){
        notice["callback"] = "callback_" + new Date().getTime();
        Cross.on(notice["callback"], callbackfunc);
      }
      var noticeStr = JSON.stringify(notice);
      win.postMessage(noticeStr, domain);
    }
  };
  $(window).on("message", function(e) {
    var realEvent = e.originalEvent,
        data = realEvent.data,
        swin = realEvent.source,
        origin = realEvent.origin,
        protocol;
    try {
      protocol = JSON.parse(data);
      var result = global.Cross.signalHandler[protocol.signal].call(null, protocol.data);
      if(!!protocol["callback"]){
        Cross.call(swin, origin, protocol["callback"], {result: result});
      }
      if(/^callback_/.test(protocol.signal)){
        delete Cross.signalHandler[protocol.signal];
      }
    } catch (e) {
      console.log(e);
      throw new Error("cross error.");
    }
  });
})(window);

父頁面 a.html

父頁面引入 jQuery 與 cross.js,點擊按鈕時通過 Cross.call 調用子頁面的 test 接口,並把目標域名作為第二個參數傳入:

<!doctype HTML>
<html>
  <head>
    <script src="jquery-1.8.3.min.js"></script>
    <script src="cross.js"></script>
    <script>
      function call_b(){
        var ifw = $("#ifr")[0].contentWindow;
        //調用iframe子頁面的公開的test接口, 子頁面域名為https://localhost:8088
        Cross.call(ifw,"https://localhost:8088","test",{t: $("#txt").val()});
      }
    </script>
  </head>
  <body>
    <input id="txt" type="text"/>
    <button onclick="call_b()">call</button>
    <iframe id="ifr" src="https://localhost:8088/b.html"></iframe>
  </body>
</html>

子頁面 b.html

子頁面只需用 Cross.on 對外公開一個名為 test 的接口,即可接收來自父頁面的調用並處理數據:

<!doctype HTML>
<html>
  <head>
    <script src="jquery-1.8.3.min.js"></script>
    <script src="cross.js"></script>
    <script>
      //對外公開一個接口命名為test
      Cross.on("test", function(data){
        alert(data.t);
      });
    </script>
  </head>
  <body>
  </body>
</html>

以上就是本文所述的 iframe 跨域調用方案,通過 postMessage 與簡單的訊號封裝,即可在遵守同源策略的前提下完成跨域方法調用與結果回傳。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved