You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Chrome扩展开发中使用setInterval实现新标签页时钟每秒刷新

Chrome新标签页时钟插件刷新问题修复方案

核心问题排查

  • 你配置的content_scripts匹配规则仅覆盖http协议页面,Chrome新标签页地址为chrome://newtab/,不在匹配范围内,main.js不会自动注入到新标签页执行
  • main.js被错误注册为后台Service Worker,Service Worker运行在无DOM环境,执行document.getElementById会直接抛出异常,打断代码运行
  • Manifest V3已不支持persistent配置项,且原manifest文件存在多余逗号语法错误
  • 新标签页入口index.html未主动引入main.js,时间更新逻辑无法运行
  • 原时间格式化仅到分钟级别,即便每秒刷新也看不到实时变化,且缺少个位数补零处理

修复步骤

1. 修正manifest.json配置

移除错误的Service Worker注册、无效的persistent配置,删除content_scripts中的main.js引入:

{
    "manifest_version": 3,
    "name": "ClockTab",
    "description": "Clock.",
    "version": "1.0.0",
    "icons": {"128": "icon_128.png"},
    "host_permissions": ["<all_urls>","activeTab","tabs"],
    "action" : {
        "default_popup": "popup.html",
        "default_icon": "icon_128.png"
    },
    "chrome_url_overrides" : {
        "newtab": "index.html"
    },
    "content_scripts": [{
        "css": ["style.css","popup.css"],
        "js": ["jquery.min.js", "popup.js","dateTime.js"],
        "all_frames": true,
        "matches": ["http://*/*"]
    }]
}

2. 调整index.html引入逻辑

在新标签页HTML中主动引入main.js:

<div id="cTime"></div>
<script src="main.js"></script>

3. 优化main.js时间更新逻辑

增加DOM加载监听、个位数补零处理,可按需选择是否展示秒数验证刷新效果:

// 等待DOM加载完成后执行逻辑
document.addEventListener('DOMContentLoaded', function() {
  // 个位数补零工具函数
  function addZero(num) {
    return num < 10 ? '0' + num : num
  }

  function updateTime() {
    const d = new Date()
    const h = addZero(d.getHours())
    const m = addZero(d.getMinutes())
    const s = addZero(d.getSeconds())
    // 不需要展示秒数可修改为 `${h}:${m}`
    const cFormat = `${h}:${m}:${s}`
    const cTime = document.getElementById("cTime")
    if (cTime) {
      cTime.textContent = cFormat
    }
  }

  // 首次加载立即执行避免1秒延迟
  updateTime()
  // 每秒触发更新
  setInterval(updateTime, 1000)
})

内容的提问来源于stack exchange,提问作者user7245847

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:27:02