同源iFrame单例

Same origin iFrame singleton

本文关键字:单例 iFrame 同源      更新时间:2023-09-26

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

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。我可以查看项目数组,并查看更改和添加。

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

我从来没能完全解决这个问题,但我走了另一条路。未来,我将使用内置的跨帧通信机制,如postMessage等。