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

开发Twitch主播开播通知浏览器扩展的两大技术问题求助

问题:Twitch开播通知浏览器扩展的两个技术难题

我正在开发一款浏览器扩展(目前针对Google Chrome,后续适配Firefox),功能是特定Twitch主播开播时推送通知。通知功能已经实现,但遇到两个技术问题:

  1. Twitch API使用问题:我知道要调用Twitch API需要用户授权获取OAuth Token,还要用到我的client-id和secret。有没有不用用户授权的替代方案?部分用户不想关联Twitch账号,而且授权流程还可能被当成钓鱼。
  2. chrome.alarms稳定性问题:我用chrome.alarms每隔X分钟检查主播状态,但Chrome文档说浏览器关闭后闹钟会被重置/删除,怎么解决这个问题?

目前我用的临时方案是爬取Twitch主播页面源码,通过查找isLiveBroadcast字符串判断是否开播,但这属于不良实践,想改用Twitch API来获取直播标题、游戏名称、封面等信息。当前判断代码如下:

async function checkIfLive(username) {
    try {
        const response = await fetch(`https://twitch.tv/${username}`);
        const sourceCode = await response.text();

        if (sourceCode.includes("isLiveBroadcast")) {
            showNotification({ message: "Is streaming", title: "Debug" });
        }
        else {
            showNotification({ message: "Is not streaming", title: "Debug" });
        }
    }
    catch (error) {
        showNotification({ message: "Error", title: "Debug" });
    }

}

let username = "<TWITCH_USERNAME>";
checkIfLive(username);

解决方案

1. 无需用户授权的Twitch API调用方案

Twitch提供的客户端凭证流(Client Credentials Flow)完全不需要用户授权,仅用你的client-id和secret就能获取应用级OAuth Token,可调用主播状态、直播信息等公开数据接口,完全符合官方规范,比爬页面源码可靠得多。

具体操作:

  • 向Twitch的token接口发送POST请求,参数包含client_id、client_secret、grant_type=client_credentials,即可获取有效期60天的Token。
  • 先用Get Users接口通过用户名查询主播的user_id,再调用Get Streams接口传入该user_id,就能拿到是否开播、直播标题、游戏名称、封面等完整数据。

2. 解决chrome.alarms浏览器关闭后重置的问题

chrome.alarms在浏览器关闭后会被清除,可结合chrome.storage.local存储闹钟配置,在扩展启动时自动重建闹钟:

  • 每次创建或更新闹钟时,将闹钟名称、触发间隔等配置保存到chrome.storage.local。
  • 在扩展的background.js中监听chrome.runtime.onStartup事件,浏览器启动时从存储中读取配置,重新创建对应闹钟。

示例代码片段:

// 保存闹钟配置到本地存储
function saveAlarmConfig(name, periodInMinutes) {
    chrome.storage.local.set({
        [name]: {
            type: "periodic",
            periodInMinutes: periodInMinutes
        }
    });
}

// 创建闹钟并同步保存配置
function createCheckAlarm(name, periodInMinutes) {
    chrome.alarms.create(name, { periodInMinutes: periodInMinutes });
    saveAlarmConfig(name, periodInMinutes);
}

// 浏览器启动时重建所有闹钟
chrome.runtime.onStartup.addListener(() => {
    chrome.storage.local.get(null, (configs) => {
        for (const [name, config] of Object.entries(configs)) {
            chrome.alarms.create(name, config);
        }
    });
});

另外,建议在扩展安装/更新时也触发一次闹钟重建,进一步确保配置不丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 08:05:54