【问题标题】:How to communicate using iframe between 2 angular apps ?如何在 2 个 Angular 应用程序之间使用 iframe 进行通信?
【发布时间】:2015-01-14 08:57:16
【问题描述】:

我有两个不同的 Angular 应用程序。我必须在“app_1”中使用 iframe 打开“app_2”的视图。 我还需要将一些数据从“app_1”发布到“app_2”。 如何在 angularJS 中实现这一点?

提前致谢。 #SOS

【问题讨论】:

  • 为什么要在两个不同的 iframe 中渲染这两个应用程序?这样做你会达到什么目的?

标签: angularjs iframe


【解决方案1】:

我会考虑使用postMessage...

在 Angular 术语中,这意味着一个应用程序将发送消息,而另一个应用程序将监听消息。

因此,在 iframe 中的应用程序上,您可以创建一个执行以下操作的工厂:

/**
 * App that sits within iframe:
 * 
 * Inject this factory into your controller and call
 * iFrame.messageParentIframe({hello: 'world'}) to send messages
 * to the parent iFrame
 */
angular
  .module('app')
  .factory('iFrameMessenger', function($window) {
    return {
      messageParentIframe: function(message) {
        $window.parent.postMessage(message, '*');
      }
    };
  });

在父 iFrame 上,您的代码应如下所示:

/**
 * App that is on parent iframe:
 *
 * Just using a controller for the sake of simplicity,
 * but you could also use a Factory that only receives
 * messages from iFrames and handle them according to each
 * action, etc. You can get creative here on how you want
 * to handle it.
 */
angular
  .module('app')
  .controller('AppCtrl', function($window) {
    $window.addEventListener('message', function() {
        // handle messages received from iframe
    });
  });

【讨论】:

  • 我想要这样的东西......非常感谢@sergiocruz :)
  • 很好的例子。我认为您应该从 AppCtrl 中的 $destroy 事件中调用 removeEventListener() 以确保没有泄漏。
  • 让对方离开怎么样(父母向孩子 iFrame 发送消息),所以我们有一个完整的例子来说明两者之间的讨论?
  • 如何从 iframe 中的应用调用 iFrame.messageParentIframe({hello: 'world'}):?这里的 iFrame 是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
  • 2020-01-06
相关资源
最近更新 更多