Home  >  Article  >  Web Front-end  >  jQuery实现跨域iframe接口方法调用_jquery

jQuery实现跨域iframe接口方法调用_jquery

WBOY
WBOYOriginal
2016-05-16 16:09:321095browse

cross.js

复制代码 代码如下:

(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

复制代码 代码如下:



 
   
   
    <script><br /> function call_b(){<br /> var ifw = $("#ifr")[0].contentWindow;<br /> //调用iframe子页面的公开的test接口, 子页面域名为<a href="http://localhost:8088">http://localhost:8088<br /> Cross.call(ifw,"<a href="http://localhost:8088","test",{t">http://localhost:8088","test",{t: $("#txt").val()});<br /> }<br /> </script>
 
 
   
   
    ">http://localhost:8088/b.html">>
 

b.html

复制代码 代码如下:



 
   
   
    <script><br /> //对外公开一个接口命名为test<br /> Cross.on("test", function(data){<br /> alert(data.t);<br /> });<br /> </script>
 
 
 

以上就是本文所述的iframe跨域的解决方案了,希望大家能够喜欢。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn