【问题标题】:Same origin iFrame singleton同源 iFrame 单例
【发布时间】:2014-04-28 11:00:51
【问题描述】:

我有一个 web 应用程序,它作为托管在单个父窗口中的多个 iframe 运行(基本上是修改后的 GWT)http://en.wikipedia.org/wiki/Google_Web_Toolkit。我试图让它们通过使用 window.parent 全局对象共享数据服务,而不是每个 iframe 单独访问我们的后端服务。我设置了这个单例模式-

define(function(){
    var DocumentService = function () {

        //create namespace if not there
        if (!parent.OurApp) {
           parent.OurApp= {};
        }
        //grab the singleton instance and return it if there
        if (parent.OurApp.DocumentService) {

            return parent.OurApp.DocumentService;
        }
        //assign the global
        parent.OurApp.DocumentService= this;

        //start fetch on instantiation
        this.items;
        this.getItems();
        this.startInterval();

    } 
    DocumentService.prototype.getItems = function(){
      //Rest service call here
      //this.items.push(response); some pseudo-code here
    };
    DocumentService.prototype.startInterval = function(){
      var self = this;
      this.intervalId = parent.setInterval(function(){
         console.log("Fetching items @ " +new Date());
         this.getitems();
      },300000);
    };
  //return new instance or singleton instance
  return new DocumentService();
});

所以这个过程在初始加载时起作用,getItems() 从服务加载数据,setInterval 启动一个循环来运行 getItems。我可以查看 items 数组并查看更改和添加。

所以现在这就是棘手的地方。如果您通过右键单击“重新加载框架”单独重新加载框架,而不是父窗口,则服务的父实例继续运行,但是当 iFrame 通过获取新的 DocumentService() 访问“父”实例单例时,线程不再同步或其他什么,因为框架不再注册控制台日志或更改项目数组。有什么理由解释为什么会发生这种情况?我的单例模式有缺陷吗?

【问题讨论】:

    标签: javascript iframe singleton


    【解决方案1】:

    我永远无法完全解决这个问题,但我走了另一条路。以后我会使用内置的跨帧通信机制,比如postMessage等。

    【讨论】:

      猜你喜欢
      • 2011-02-11
      • 1970-01-01
      • 2013-05-15
      • 2016-11-13
      • 2015-09-19
      • 1970-01-01
      • 2014-08-13
      • 1970-01-01
      • 2021-08-28
      相关资源
      最近更新 更多