You need to enable JavaScript to run this app. 如何让Chrome扩展程序脚本在后台持续运行不随弹窗关闭终止
优惠活动
大模型
产品
解决方案
定价
更多

如何让Chrome扩展程序脚本在后台持续运行不随弹窗关闭终止

问题根因

你当前的倒计时、定时器逻辑都写在popup.js中,Chrome扩展的popup页面属于临时上下文,只要关闭弹窗页面就会被浏览器完全销毁,页面内所有的定时器、变量都会被清空,这是功能失效的核心原因。
扩展的background(后台)上下文是常驻运行的,不会随popup关闭而销毁,把定时逻辑迁移到background即可解决问题。

具体修改方案

1. 修改popup.js

移除popup内的倒计时逻辑,点击按钮时仅将用户设置的时分秒参数传递给后台即可:

console.log("popup.js loaded")

document.addEventListener('DOMContentLoaded', function () {
  const input_h = document.getElementById("input-hour");
  const input_m = document.getElementById("input-min");
  const input_s = document.getElementById("input-sec");
  const ss_button = document.getElementById("ss_button");

  // 恢复历史设置
  if(input_h) input_h.value = localStorage.getItem("hour_value");
  if(input_m) input_m.value = localStorage.getItem("min_value");
  if(input_s) input_s.value = localStorage.getItem("sec_value");

  ss_button?.addEventListener('click', ss_clickHandler);
  
  function ss_clickHandler(e) {
    // 保存设置到本地
    localStorage.setItem("hour_value", input_h.value);
    localStorage.setItem("min_value", input_m.value);
    localStorage.setItem("sec_value", input_s.value);
  
    const refresh_hour = parseInt(input_h.value);
    const refresh_min = parseInt(input_m.value);
    const refresh_sec = parseInt(input_s.value);

    // 传递时间参数给后台
    chrome.runtime.sendMessage({
      message: "setRefresh",
      hours: refresh_hour,
      minutes: refresh_min,
      seconds: refresh_sec
    });
  }
});

2. 修改background.js

在后台实现倒计时、定时逻辑,新增定时器重置能力避免重复设置任务:

// 存储当前定时器ID,用于重置任务
let refreshTimer = null;

chrome.runtime.onMessage.addListener( function(request,sender,sendResponse) {
    // 处理定时刷新设置请求
    if( request.message === "setRefresh" ) {
        const {hours, minutes, seconds} = request;
        // 清空已有定时器,避免重复触发
        if(refreshTimer) clearTimeout(refreshTimer);

        const now = new Date();
        const then = new Date();
        const oneSecond = 1000;
    
        // 若当前时间已过设置时间,自动顺延到次日
        if(now.getHours() > hours ||
            (now.getHours() == hours && now.getMinutes() > minutes) ||
            (now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds)) {
            then.setDate(now.getDate() + 1);
        }
    
        then.setHours(hours);
        then.setMinutes(minutes);
        then.setSeconds(seconds);
        const timeout = then.getTime() - now.getTime() - oneSecond;

        // 后台设置定时器,不受popup关闭影响
        refreshTimer = setTimeout(() => {
            chrome.tabs.getSelected(null, function(tab) {
                chrome.tabs.executeScript(tab.id, {code: 'window.location.reload(true);'});
            });
        }, timeout);
    }

    // 原有重载逻辑保留
    if( request.message === "reload" ) {
        chrome.tabs.getSelected(null, function(tab) {
          chrome.tabs.executeScript(tab.id, {code: 'window.location.reload(true);'});
        });
    }
});
补充说明

如果你的扩展使用Manifest V3版本,只需将chrome.tabs.getSelected替换为chrome.tabs.query({active: true, currentWindow: true})获取当前活跃标签即可,其余逻辑通用。


内容的提问来源于stack exchange,提问作者Teo F.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 13:54:04