首页 > 解决方案 > 如何避免调用 postmessage

问题描述

在我的应用程序中,我具有使用 setInterval 的倒计时功能,如下所示:

     this.timer = window.setInterval(() => {
        const time_delta = (this.target_date - new Date() ) / 1000
        if (time_delta > 0) {
            this.days = time_delta / (24 * 3600)
            this.hour = time_delta  % (24 * 3600) / (3600)
            this.minute = (time_delta  % (24 * 3600) % (3600)) / 60
            this.second = time_delta % 60
        } else {
            this.days = 0
            this.hour = 0
            this.minute = 0
            this.second = 0
        }

        if(time_delta <= 1 && time_delta > 0 ){
            clearInterval(this.timer);
            location.reload();
        }
    },10000)

现在还有另一个功能完全不同,它继承了 postmessage

   (function (window, undefined) {
function MessageChannel(group, targetWindow, origin) {
    this._msgNo = 1;
    this._group = group;
    this._origin = '*' || origin;
    this._requestHandler = {};
    this._messageQueue = {};
    this._targetWindow = targetWindow || window.parent;

    window.addEventListener('message', receiveMessage.bind(this), false);
}
 MessageChannel.prototype.subscribeRequestMessage = function (msg, callback) {
    // Some logic
};
  MessageChannel.prototype.unsubscribeRequestMessage = function (msg, callback) {
   // Some logic
};
MessageChannel.prototype.postMessage = function (msg, data, timeout) {
    // Some logic
};
 function receiveMessage(event) {
  // Some logic

}

window.Granite = window.Granite || {};
window.Granite.author = window.Granite.author || {};
window.Granite.author.MessageChannel = MessageChannel;

}(this));   

我遇到的问题是,只要 setInterval 在倒数计时器中每秒钟执行一次,那么 MessageChannel.prototype.postMessage 函数也会执行。

倒数计时器是 html 页面的 iFrame 中存在的一个组件,该页面还具有 MessageChannel.prototype.postMessage 的代码,并且它可以由我用来构建页面的框架/工具全局使用。每当组件发生变化时,框架都会触发 MessageChannel.prototype.postMessage。在这种情况下,计时器值会发生变化,从而触发 postMessage 调用。我不想执行 MessageChannel.prototype.postMessage 代码。我怎样才能避免这种情况?

标签: javascriptpostmessage

解决方案


推荐阅读