简体   繁体   English

持续在setInterval中将消息从background.js发送到popup.js,但仅在打开弹出窗口时才发送?

[英]Continually send message from background.js to popup.js in setInterval but only when popup is opened?

I am a beginner. 我是初学者。 I am trying to write a simple extension. 我正在尝试编写一个简单的扩展。 The idea is running a countdown timer in background.js and display it in the popup.html. 这个想法是在background.js中运行一个倒数计时器,并在popup.html中显示它。 I write some code below. 我在下面写一些代码。

background.js background.js

function countdown() {
    window.intervalId = setInterval(function() {
        window.remaining_time -= 1000;
        chrome.runtime.sendMessage(JSON.stringify(get_status()), function(response) {
            console.log("Respond receive!");
        })
    }, 1000)
}

popup.js popup.js

chrome.runtime.onMessage.addListener(
    function(msg, sender, sendResponse) {
        console.log("message received: " + msg);
        if (msg == "Background port started!") {
            return;
        }
        let timer_status = JSON.parse(msg);
        let remaining_time = timer_status.remaining_time;
        let curr_mode = timer_status.curr_mode;
        let timer_state = timer_status.timer_state;

        var days = Math.floor(remaining_time / (1000 * 60 * 60 * 24));
        var hours = Math.floor((remaining_time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var mins = Math.floor((remaining_time % (1000 * 60 * 60)) / (1000 * 60));
        var secs = Math.floor((remaining_time % (1000 * 60)) / 1000);

        var countdown_str = "";
        if (days > 0) {
            countdown_str += days + " days ";
        }
        if (hours > 0) {
            countdown_str += hours + " hours ";
        }
        if (mins > 0) {
            countdown_str += mins + " mins ";
        }
        countdown_str += secs + " secs";
        document.getElementById("countdown").innerHTML = countdown_str;
        sendResponse({farewell:"Goodbye"});
    }
)

The code running fine when the popup is open. 打开弹出窗口时,代码运行良好。 However, when the popup is closed, the problem occured as "Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist". 但是,当关闭弹出窗口时,出现问题为“未经检查的runtime.lastError:无法建立连接。接收端不存在”。

I've looked for popup closing event but it seems not to exist. 我一直在寻找弹出窗口关闭事件,但似乎不存在。 So my question is are there any ELEGANT way to continually send messages from background.js to popup.js in setInterval but only when the popup script is opened? 所以我的问题是在那里不断background.js发送消息中的setInterval到popup.js但只有当弹出脚本打开任何优雅的方式?

If the popup is not open this will fail and abort the execution of the sendresponse 如果弹出窗口未打开,将失败并中止sendresponse的执行

     document.getElementById("countdown").innerHTML = countdown_str;
     sendResponse({farewell:"Goodbye"});

either use try 要么尝试

    try{
         var test=   document.getElementById("countdown");
         if(test){ test.innerHTML= countdown_str;}

         }catch (ex){
             console.log(ex);
             console.log(typeof(test)); //also a possible way to check
     }

or check it something like this 或检查像这样

           if(document.body.contains(document.getElementById('test'))){
              alert('Element exists!');
           } else{
              alert('Element does not exist!');
           }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM