未调用事件侦听器回调函数

Event Listener call back function not called

我正在尝试将自定义事件从 iFrame 源发送到 parent。 我已经提到 Html5 - Cross Browser Iframe postmessage - child to parent?,但我仍然无法将活动发送到我的 parent。

下面是 iFrame 源代码,我将事件发送到 parent:

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

在我的 parent 中,我有 angularJS 控制器文件,我试图在其中收听此事件:

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");
        }

}]);

这里是 html 文件:

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

我是不是做错了什么?我在浏览器控制台中没有看到任何错误。 请帮忙!

postMessage 发送一个 message 事件,而不是 onWidgetDisplayed 事件,所以你想挂钩 message 事件。如果您需要发送多种类型的消息,您可以传递任意 JavaScript 值作为事件数据。您已经传递了一个字符串,因此:

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);