Chrome扩展无法保存JSON:Twitch直播游戏变更通知功能求助
Hey there! As someone who’s comfortable with C# but navigating JavaScript for your Twitch Chrome extension, I totally get how the browser environment’s quirks can throw you off—let’s fix that JSON storage issue so you can get those game-change notifications working properly.
First, let’s align on the right tool for the job: Chrome extensions have a dedicated storage API (chrome.storage.local) that’s designed for this exact use case, and it handles JSON serialization/deserialization automatically. Most likely, the issue stems from either missing permissions, mishandling async code (a common pain point coming from C#’s sync-heavy workflow), or not initializing your stored data correctly.
Step 1: Make Sure You Have the Required Permission
First thing to check: your manifest.json must declare the storage permission, otherwise Chrome will block all storage API calls. Add this to your manifest:
{ "manifest_version": 3, // or 2 if you're using the older version "permissions": ["storage", "notifications"], // ... rest of your manifest }
Note: If you’re using Manifest V3, make sure your service worker has access to the storage API (it does by default if the permission is declared).
Step 2: Correctly Use the Chrome Storage API (Async-First!)
Unlike C# where you might read/write files synchronously, Chrome’s storage API is async. That means you can’t just call get() and immediately use the data—you need to use async/await or callbacks to wait for the operation to finish.
Here’s a complete example tailored to your use case (tracking notified games to avoid duplicates):
// Async function to handle game change logic async function handleGameSwitch(currentGameId, currentGameName) { try { // 1. Fetch existing notified games from storage const storedData = await chrome.storage.local.get('notifiedGames'); // Initialize with an empty array if no data exists yet const notifiedGames = storedData.notifiedGames || []; // 2. Check if we've already notified for this game if (!notifiedGames.includes(currentGameId)) { // 3. Send the notification await chrome.notifications.create({ type: 'basic', iconUrl: 'icons/your-icon.png', // Replace with your extension's icon title: '主播切换游戏啦!', message: `现在正在玩:${currentGameName}` }); // 4. Update the list and save it back to storage notifiedGames.push(currentGameId); await chrome.storage.local.set({ notifiedGames: notifiedGames }); } } catch (error) { console.error('处理游戏切换时出错:', error); // Check for Chrome-specific errors (like permission issues) if (chrome.runtime.lastError) { console.error('Chrome API 错误:', chrome.runtime.lastError.message); } } }
Common Pitfalls to Avoid
- Forgetting async/await: If you skip
awaitonchrome.storage.local.get()orset(), your code will try to use data that hasn’t loaded yet, leading to empty or undefined values. - Manual JSON serialization: You don’t need to call
JSON.stringify()orJSON.parse()withchrome.storage—the API automatically handles converting JS objects to JSON and back. - Not initializing default values: The first time your extension runs,
notifiedGameswon’t exist in storage. UsingstoredData.notifiedGames || []ensures you always have a valid array to work with. - Ignoring errors: Always check the console for errors—Chrome will log permission issues or API misuse there, which can save you hours of debugging.
Testing the Storage
To verify your data is saving correctly:
- Open your extension’s background page/service worker in Chrome DevTools
- Go to the Application tab (or Storage in older versions)
- Expand Chrome Storage > Local—you should see your
notifiedGamesarray listed there after a game change.
This should resolve your JSON storage issue and let you implement the one-time notification logic smoothly. Let me know if you hit any specific snags with the Twitch API integration or other parts of the extension!
内容的提问来源于stack exchange,提问作者Rui

