网络编程 
首页 > 网络编程 > 浏览文章

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

(编辑:jimmy 日期: 2026/3/5 浏览:3 次 )

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

复制代码 代码如下:
<!doctype HTML>
<html>
  <head>
    <script src="/UploadFiles/2021-04-02/jquery-1.8.3.min.js">     <script src="cross.js">     <script>
      function call_b(){
        var ifw = $("#ifr")[0].contentWindow;
        //调用iframe子页面的公开的test接口, 子页面域名为http://localhost:8088
        Cross.call(ifw,"http://localhost:8088","test",{t: $("#txt").val()});
      }
    </script>
  </head>
  <body>
    <input id="txt" type="text"/>
    <button onclick="call_b()">call</button>
    <iframe id="ifr" src="/UploadFiles/2021-04-02/b.html">   </body>
</html>

b.html

复制代码 代码如下:
<!doctype HTML>
<html>
  <head>
    <script src="/UploadFiles/2021-04-02/jquery-1.8.3.min.js">     <script src="cross.js">     <script>
    //对外公开一个接口命名为test
    Cross.on("test", function(data){
      alert(data.t);
    });
    </script>
  </head>
  <body>
  </body>
</html>

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

上一篇:jQuery.Highcharts.js绘制柱状图饼状图曲线图
下一篇:Flash图片上传组件 swfupload使用指南
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。