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

如何开发每日指定时间自动运行并打开特定URL的Chrome扩展

Chrome扩展实现每日定时自动打开指定URL指南

一、先修正manifest.json的语法错误

你当前的manifest配置存在两处小问题:

  1. content_scripts里的matches行末尾缺少逗号,会导致JSON解析失败;
  2. version字段值为0不符合Chrome扩展的版本规范,建议改为0.1这类合法格式。

如果你的需求只是定时打开URL,不需要向目标页面注入脚本,可以直接移除content_scripts部分。修正后的manifest示例:

{
    "manifest_version": 3,
    "name": "Bot",
    "version": "0.1",
    "permissions": ["tabs", "alarms", "storage"],
    "background": {
        "service_worker": "background.js"
    }
}

如果确实需要注入脚本,补全逗号并确保matches是合法的URL匹配模式(比如"https://example.com/*")即可。

二、编写background.js实现定时逻辑

利用Chrome的alarms API实现每日定时触发,结合tabs API打开目标URL,具体代码如下:

// 扩展安装/更新时初始化定时闹钟
chrome.runtime.onInstalled.addListener(() => {
    // 清除旧闹钟避免重复
    chrome.alarms.clear('dailyOpenURL', () => {
        // 设置每日午夜触发的重复闹钟
        chrome.alarms.create('dailyOpenURL', {
            when: getNextMidnight(),
            periodInMinutes: 1440 // 24小时=1440分钟,每日重复
        });
    });
});

// 监听闹钟触发事件
chrome.alarms.onAlarm.addListener((alarm) => {
    if (alarm.name === 'dailyOpenURL') {
        // 替换成你需要打开的指定URL
        const targetURL = 'https://your-target-url.com';
        // 创建新标签页打开URL
        chrome.tabs.create({ url: targetURL });
    }
});

// 计算下一个午夜的时间戳(毫秒)
function getNextMidnight() {
    const now = new Date();
    const nextMidnight = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0);
    return nextMidnight.getTime();
}

三、自定义触发时间(可选)

如果需要改为其他时间(比如每天早上9点),替换getNextMidnight函数为以下逻辑:

// 计算指定小时的下一次触发时间
function getNextTargetTime(targetHour = 9) {
    const now = new Date();
    const targetTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), targetHour, 0, 0);
    // 如果当前时间已过目标时间,自动顺延到第二天
    if (now.getTime() > targetTime.getTime()) {
        targetTime.setDate(targetTime.getDate() + 1);
    }
    return targetTime.getTime();
}

然后在创建闹钟时改为when: getNextTargetTime(9)即可。

四、测试技巧

测试时可以临时把periodInMinutes改为1(1分钟触发一次),验证功能正常后再改回1440。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 01:45:25