【问题标题】:Event Listener call back function not called未调用事件侦听器回调函数
【发布时间】:2018-10-05 16:17:28
【问题描述】:

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

下面是我将事件发送给父级的 iFrame 源代码:

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

在我的父母中,我有 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> 

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

【问题讨论】:

标签: javascript addeventlistener postmessage dom-events


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 2017-07-15
    • 2015-07-01
    • 2015-04-05
    • 2018-08-06
    相关资源
    最近更新 更多