简体   繁体   中英

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. I write some code below.

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

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".

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?

If the popup is not open this will fail and abort the execution of the 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!');
           }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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