-1

I'm trying to send a custom event from iFrame source to the parent. I've referred to Html5 - Cross Browser Iframe postmessage - child to parent? but I'm still not able to get the event to my parent.

Below is the code from iFrame source where I'm sending the event to the parent:

window.parent.postMessage('onWidgetDisplayed', '*');

In my parent, I have the angularJS controller file where I'm trying to listen to this event:

angular.module('common.controllers.vaultV2', [])
.controller('VaultV2Controller', ['$scope', '$rootScope', '$sce', function($scope, $rootScope, $sce) {

        $scope.iframeUrl = $sce.trustAsResourceUrl("https://some-url");

        window.addEventListener('onWidgetDisplayed', onWidgetDisplayedEvent, false);

        function onWidgetDisplayedEvent() {
            alert("onWidgetDisplayed event received at parent");
        }

}]);

And here is the html file:

<div style="align: center">
    <iframe id="vault" ng-src="{{iframeUrl}}" style="width: 100%; height: 300px;  overflow: hidden" target="_parent"></iframe>
</div> 

Am I doing something wrong? I don't see any errors in the browser console. Please help!

eureka19
  • 2,731
  • 5
  • 26
  • 34

1 Answers1

1

postMessage sends a message event, not an onWidgetDisplayed event, so you'd want to hook the message event. If you need to send multiple types of messages, you can pass any arbitrary JavaScript value as the event data. You're already passing a string, so:

window.addEventListener("message", function(e) {
    if (/* check `e.origin` and make sure you're happy with it*/) {
        if (e.data === "onWidgetDisplayed") {
            onWidgetDisplayed.call(this, e);
        }
    }
}, false);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875