簡體   English   中英

持續在setInterval中將消息從background.js發送到popup.js,但僅在打開彈出窗口時才發送?

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

我是初學者。 我正在嘗試編寫一個簡單的擴展。 這個想法是在background.js中運行一個倒數計時器,並在popup.html中顯示它。 我在下面寫一些代碼。

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

打開彈出窗口時,代碼運行良好。 但是,當關閉彈出窗口時,出現問題為“未經檢查的runtime.lastError:無法建立連接。接收端不存在”。

我一直在尋找彈出窗口關閉事件,但似乎不存在。 所以我的問題是在那里不斷background.js發送消息中的setInterval到popup.js但只有當彈出腳本打開任何優雅的方式?

如果彈出窗口未打開,將失敗並中止sendresponse的執行

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

要么嘗試

    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
     }

或檢查像這樣

           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