Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to communicate using iframe between 2 angular apps ?

I have two different angular apps. I have to open a view of 'app_2' using iframe in 'app_1'. I also need to post some data from 'app_1' to 'app_2'. How to achieve this in angularJS?

Thanks in advance. #SOS

like image 433
Vaibhav Pachauri Avatar asked Jan 14 '15 08:01

Vaibhav Pachauri


Video Answer


1 Answers

I would use consider using postMessage...

In Angular terms this would mean that one app would send messages and the other one would be listening to messages.

So on the App that sits within the iframe you can make a factory that does the following:

/**
 * 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, '*');
      }
    };
  });

On the parent iFrame your code should look something like this:

/**
 * 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
    });
  });
like image 119
sergiocruz Avatar answered Sep 25 '22 01:09

sergiocruz