如何每秒提取浏览器LocalStorage指定键值并存储?
Absolutely feasible! I’ve tackled similar dynamic LocalStorage monitoring tasks before, and here are a few practical solutions depending on your setup:
1. Quick Test with Browser DevTools Console
If you just want to validate the workflow temporarily, paste this script directly into your browser’s DevTools Console (hit F12 > navigate to the Console tab):
// Set up a 1-second interval to check for updates const monitorInterval = setInterval(() => { const abcValue = localStorage.getItem('ABC'); if (abcValue) { console.log('Current ABC value:', abcValue); // Pass the value to your storage logic persistData(abcValue); } else { console.log('ABC key not found in LocalStorage'); } }, 1000); // Example: Send data to a backend API function persistData(value) { fetch('/your-backend-endpoint/save-abc', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: value, timestamp: new Date().toISOString() }) }) .then(res => res.json()) .then(() => console.log('Data saved successfully')) .catch(err => console.error('Save failed:', err)); } // To stop monitoring later: clearInterval(monitorInterval);
Note: This script will stop running if you refresh the page or close the tab. For persistent monitoring, use a userscript.
2. Persistent Monitoring with Tampermonkey Userscript
For a solution that stays active across page reloads and works on your target site, use a userscript manager like Tampermonkey:
- Install Tampermonkey for your browser
- Create a new userscript and paste this code:
// ==UserScript== // @name LocalStorage ABC Monitor // @namespace http://tampermonkey.net/ // @version 0.1 // @description Track and save LocalStorage "ABC" updates every second // @author Your Name // @match *://your-target-site.com/* // Replace with your actual site URL // @grant GM_xmlhttpRequest // ==/UserScript== (function() { 'use strict'; // Check for updates every 1 second setInterval(() => { const abcValue = localStorage.getItem('ABC'); if (abcValue) { console.log('Fetched ABC:', abcValue); // Send data to your backend (Tampermonkey handles CORS automatically) GM_xmlhttpRequest({ method: 'POST', url: 'https://your-backend-url.com/save', headers: { 'Content-Type': 'application/json' }, data: JSON.stringify({ value: abcValue, timestamp: new Date().toISOString(), pageUrl: window.location.href }), onload: (res) => console.log('Data saved:', res.responseText), onerror: (err) => console.error('Save error:', err) }); // Alternative: Append to a local text file (limited browser support) // const blob = new Blob([`${new Date().toISOString()}: ${abcValue}\n`], { type: 'text/plain' }); // const downloadLink = document.createElement('a'); // downloadLink.href = URL.createObjectURL(blob); // downloadLink.download = 'abc-log.txt'; // downloadLink.click(); // URL.revokeObjectURL(downloadLink.href); } }, 1000); })();
Remember to replace
your-target-site.comwith the actual domain you’re monitoring, andyour-backend-url.com/savewith your backend endpoint.
3. Full Control with an Electron Desktop App
If you need to save data directly to a local database/file without relying on a backend, build a simple Electron app:
Step-by-Step Setup:
- Initialize the project:
npm init -y npm install electron --save-dev
- Create
main.js(Electron main process):
const { app, BrowserWindow, ipcMain } = require('electron'); const fs = require('fs'); const path = require('path'); let mainWindow; function createWindow() { mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true, contextIsolation: false } }); mainWindow.loadURL('https://your-target-site.com'); // Load your target page // Listen for data from the browser renderer process ipcMain.on('abc-data', (_, value) => { // Append to a local text file fs.appendFileSync( path.join(__dirname, 'abc-history.txt'), `${new Date().toISOString()}: ${value}\n` ); // Optional: Save to SQLite database // const sqlite3 = require('sqlite3').verbose(); // const db = new sqlite3.Database('abc-db.db'); // db.run('INSERT INTO values (content, timestamp) VALUES (?, ?)', [value, new Date().toISOString()]); }); } app.whenReady().then(createWindow);
- Create
renderer.js(runs in the browser context):
const { ipcRenderer } = require('electron'); setInterval(() => { const abcValue = localStorage.getItem('ABC'); if (abcValue) { console.log('Fetched ABC:', abcValue); ipcRenderer.send('abc-data', abcValue); } }, 1000);
- Add a start script to
package.json:
"scripts": { "start": "electron ." }
- Launch the app:
npm start
Pro Tip: More Efficient Monitoring
Instead of polling every second, you can use the storage event to detect updates instantly (note: this only triggers when LocalStorage is modified from another tab/window):
window.addEventListener('storage', (event) => { if (event.key === 'ABC') { console.log('ABC updated:', event.newValue); persistData(event.newValue); } });
For same-tab updates, wrap the localStorage.setItem method to trigger your own custom event.
内容的提问来源于stack exchange,提问作者Prasanna Chakravarthi

