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

Electron应用开发控制台无法访问localStorage?Discord数据自动存储求解

Hey there! Let's figure out how to solve your problem—since Discord is built on Electron, we can leverage its unique features to get your data-saving workflow working, even without localStorage.

Why localStorage isn't working

Discord's renderer process (the part that runs the UI and where your dev console lives) likely disables localStorage intentionally for security or sandboxing reasons. That's why you're seeing the "not defined" error, even when trying window.localStorage. No worries though—we have better options for your unattended data-writing goal.

Solution: Use Node.js APIs directly (best for unattended writes)

Electron lets renderer processes access Node.js core modules (like file system tools) by default (unless strict sandboxing is enabled, which Discord doesn't enforce for its own processes). This is perfect for saving data to disk on a timer.

Here's a practical script you can run directly in the dev console:

// Import Node.js modules we need
const fs = require('fs').promises;
const path = require('path');
const os = require('os');

// Configure your settings
const intervalSeconds = 60; // Replace with your desired interval
const saveFilePath = path.join(os.homedir(), 'discord-collected-data.json');

// Define your data-fetching logic (customize this!)
function getDiscordData() {
  // Replace this with how you actually extract data from Discord's UI/state
  // Example: Grab channel name, unread counts, etc.
  return {
    timestamp: new Date().toISOString(),
    activeChannel: document.querySelector('.channel-name')?.textContent.trim(),
    unreadCount: document.querySelectorAll('.unread').length
  };
}

// Set up the unattended timer
const saveInterval = setInterval(async () => {
  try {
    // Fetch the latest data
    const data = getDiscordData();
    
    // Read existing data (if any) to append instead of overwriting (optional)
    let existingData = [];
    try {
      const fileContent = await fs.readFile(saveFilePath, 'utf8');
      existingData = JSON.parse(fileContent);
    } catch (err) {
      // No existing file? That's okay, start fresh
      console.log('No existing data file found, creating new one');
    }
    
    // Add new data entry
    existingData.push(data);
    
    // Write back to disk
    await fs.writeFile(saveFilePath, JSON.stringify(existingData, null, 2), 'utf8');
    console.log(`Data saved successfully! Path: ${saveFilePath}`);
  } catch (error) {
    console.error('Failed to save data:', error);
  }
}, intervalSeconds * 1000);

// To stop the timer later (if needed), run:
// clearInterval(saveInterval);

Key notes for this approach:

  • Customize getDiscordData(): This is where you'll put your actual logic to extract data from Discord's interface or internal state. Use DevTools element inspection to find selectors for the data you need.
  • Append vs overwrite: The script above appends new data entries instead of overwriting the file—adjust this if you prefer to store only the latest snapshot.
  • Permissions: Make sure the path you're writing to (like your home directory) has write permissions.

If Node.js APIs are blocked (fallback: IndexedDB)

In the rare case Discord has locked down Node.js access in the renderer process, you can use IndexedDB (a browser-built-in database) to store data temporarily, then add logic to export it to a file later. Here's a quick example:

// Set up IndexedDB storage
async function initDB() {
  return new Promise((resolve, reject) => {
    const dbRequest = indexedDB.open('DiscordDataStore', 1);
    dbRequest.onupgradeneeded = (e) => {
      const db = e.target.result;
      db.createObjectStore('savedData', { keyPath: 'timestamp' });
    };
    dbRequest.onsuccess = (e) => resolve(e.target.result);
    dbRequest.onerror = (e) => reject(e.target.error);
  });
}

// Save data to IndexedDB
async function saveDataToDB(data) {
  const db = await initDB();
  const tx = db.transaction('savedData', 'readwrite');
  tx.objectStore('savedData').add(data);
  await tx.complete;
}

// Set up the timer
setInterval(async () => {
  const data = getDiscordData(); // Reuse the same data-fetching function from earlier
  await saveDataToDB(data);
  console.log(`Data stored in IndexedDB: ${JSON.stringify(data)}`);
}, intervalSeconds * 1000);

This is less ideal for unattended use, but it works if Node.js access is restricted.

Final tips

  • Discord updates: Keep in mind that Discord frequently updates its UI, so your data-selector logic might break after an update. You'll need to adjust the selectors in getDiscordData() if that happens.
  • Long-term stability: For extended unattended use, consider wrapping this logic in a small Electron extension or standalone script instead of relying on the dev console (which might close if Discord restarts).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:36:57