Child & Parent iframe communication

Date: 2017-02-01
define(['bluebird', 'jquery'], function () {
    var Promise = require('bluebird');
    var $ = require('jquery');

    var getWindowFromElement = function(element) {
		var $e = $(element);
		var e = $e[0];
		var doc = e.ownerDocument;
		var win = doc.defaultView || doc.parentWindow;
		return win;
	};

    var defer = function() {
        var res, rej;
        var promise = new Promise(function(resolve, reject) {
            res = resolve;
            rej = reject;
        });
        return {
            promise: promise,
            resolve: res,
            reject: rej,
        };
    };

    var ParentWidget = function($parent, settings) {
        this.init($parent, settings);
    };

    ParentWidget.prototype.init = function($parent, settings) {
        var self = this;
        self.$parent = $parent;
        self.window = getWindowFromElement($parent);
        self.$frame = $(''); self.$parent.append(this.$frame); self.settings = settings; self.deferInitialized = defer(); self.deferLoaded = defer(); self.deferPlayed = defer(); self.lastMessage = new Date(); // for timeout and hang calculation self.window.addEventListener("message", function(event) { return self.onMessage(event); }, false); }; ParentWidget.prototype.sendMessage = function(message) { var self = this; var str = JSON.stringify(message); //console.log('Parent: Send:', str); self.$frame[0].contentWindow.postMessage(str, '*'); }; ParentWidget.prototype.onMessage = function(event) { var self = this; if (event.source === self.$frame[0].contentWindow) { try { //console.log('Parent: Received:', event.data); self.lastMessage = new Date(); // widget is still busy sending messages to us var data = JSON.parse(event.data); switch(data.widgetEvent) { case 'initialized': self.deferInitialized.resolve(); break; case 'loaded': self.deferLoaded.resolve(); break; case 'played': self.deferPlayed.resolve(); break; } } catch(e) { // !ignore any json errors } } }; ParentWidget.prototype.load = function() { var self = this; return self.deferInitialized.promise.timeout(10000).then(function() { self.sendMessage({ widgetAction: 'load', settings: self.settings }); return self.deferLoaded.promise; }) .catch(Promise.TimeoutError, function(e) { console.log("Could not load widget in 10000ms"); return Promise.resolve(); }); }; ParentWidget.prototype.play = function() { var self = this; self.sendMessage({ widgetAction: 'play', settings: self.settings }); var playTimeout = self.settings.duration; if (playTimeout < 1) { return self.deferPlayed.promise; } else { return self.deferPlayed.promise.timeout(playTimeout) .catch(Promise.TimeoutError, function(e) { return Promise.resolve(); }); } }; return ParentWidget; });
define(['bluebird'], function () {
    var Promise = require('bluebird');

    var ChildWidget = function() {
        this.init();
    };

    ChildWidget.prototype.init = function() {
        var self = this;
        self.settings = {};

        window.addEventListener("message", function(event) {
            return self.onMessage(event);
        }, false);
    };

    ChildWidget.prototype.sendMessage = function(message) {
        var str = JSON.stringify(message);
        //console.log('Child: Send:', str);
        window.parent.postMessage(str, '*');
    };

    ChildWidget.prototype.onMessage = function(event) {
        var self = this;
        if (event.source === window.parent.parent || event.source === window.parent) {
            try {
                //console.log('Child: Received:', event.data);
                var data = JSON.parse(event.data);
                switch(data.widgetAction) {
                    case 'load': self.load(data.settings); break;
                    case 'play': self.play(); break;
                }
            } catch(e) {
                // !ignore any json errors
            }
        }
    };

    ChildWidget.prototype.sendInitialized = function(settings) {
        var self = this;
        self.sendMessage({ widgetEvent: 'initialized' });
    };

    ChildWidget.prototype.load = function(settings) {
        var self = this;
        self.settings = settings;
        if (typeof self.onload === 'function') {
            self.onload();
        }
    };

    ChildWidget.prototype.setLoaded = function(settings) {
        var self = this;
        self._loaded = true;
        self.sendMessage({ widgetEvent: 'loaded' });
    };

    ChildWidget.prototype.play = function() {
        var self = this;
        if (typeof self.onplay === 'function') {
            self.onplay();
        }
    };

    ChildWidget.prototype.setPlayed = function(settings) {
        var self = this;
        self._played = true;
        self.sendMessage({ widgetEvent: 'played' });
    };

    return ChildWidget;
});

6040cookie-checkChild & Parent iframe communication