Chrome扩展本地保存屏蔽万智牌名称至TXT文件方案问询
解决Chrome扩展本地持久化屏蔽万智牌名称的问题
Chrome扩展出于浏览器安全模型限制,无法直接写入本地TXT文件(除非触发用户主动下载,但频繁下载体验极差)。最适合你的方案是使用Chrome官方提供的chrome.storage.local API实现本地持久化,这是专门为扩展设计的本地存储方案,操作简单且体验流畅。
步骤1:配置扩展权限
首先在你的manifest.json中添加storage权限(以Manifest V3为例):
{ "manifest_version": 3, "name": "万智牌屏蔽工具", "version": "1.0", "permissions": ["storage", "activeTab"], "content_scripts": [ { "matches": ["*://你的目标商店域名/*"], "js": ["content.js"] } ] }
(替换你的目标商店域名为你要操作的商店页面域名,比如*.example.com/*)
步骤2:实现存储与读取逻辑
替换你原来的appendName函数,用chrome.storage.local来管理屏蔽列表:
// 添加卡牌到屏蔽列表(自动去重) async function appendName(cardName) { // 读取已存储的屏蔽列表,默认返回空数组 const { blockedCards = [] } = await chrome.storage.local.get('blockedCards'); if (!blockedCards.includes(cardName)) { blockedCards.push(cardName); // 保存更新后的列表到本地 await chrome.storage.local.set({ blockedCards }); console.log(`已屏蔽卡牌: ${cardName}`); } } // 读取屏蔽列表(用于页面加载时隐藏对应卡牌) async function getBlockedCards() { const { blockedCards = [] } = await chrome.storage.local.get('blockedCards'); return blockedCards; }
步骤3:完善页面交互逻辑
修改你的点击事件处理,并添加页面加载时的自动屏蔽逻辑:
// 处理按钮点击,添加屏蔽并立即隐藏卡牌 async function handleButtonClick(event) { const cardName = event.target.id; await appendName(cardName); // 根据页面实际结构调整选择器,隐藏当前卡牌元素 const cardElement = document.getElementById(cardName); if (cardElement) { cardElement.style.display = 'none'; } } // 页面加载完成后,自动隐藏所有已屏蔽的卡牌 document.addEventListener('DOMContentLoaded', async () => { const blockedCards = await getBlockedCards(); blockedCards.forEach(cardName => { const cardElement = document.getElementById(cardName); if (cardElement) { cardElement.style.display = 'none'; } }); }); // 绑定所有屏蔽按钮的点击事件 const buttons = document.querySelectorAll('button.block-button'); buttons.forEach(button => { button.addEventListener('click', handleButtonClick); });
可选:添加屏蔽列表导出功能(用于备份)
如果需要将屏蔽列表导出为TXT文件做备份,可以添加一个导出按钮(比如放在页面角落或扩展弹出页),一次性生成下载:
// 导出屏蔽列表为TXT async function exportBlockedCards() { const { blockedCards = [] } = await chrome.storage.local.get('blockedCards'); const textContent = blockedCards.join('\n'); const blob = new Blob([textContent], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const exportLink = document.createElement('a'); exportLink.href = url; exportLink.download = 'blocked-magic-cards.txt'; exportLink.click(); URL.revokeObjectURL(url); } // 示例:创建导出按钮并固定在页面右上角 const exportBtn = document.createElement('button'); exportBtn.textContent = '导出屏蔽列表'; exportBtn.style.position = 'fixed'; exportBtn.style.top = '10px'; exportBtn.style.right = '10px'; exportBtn.addEventListener('click', exportBlockedCards); document.body.appendChild(exportBtn);
方案优势
- 体验流畅:所有存储操作在后台完成,无需用户手动选择文件或重复触发下载。
- 持久化可靠:数据会一直保存,直到用户清除扩展数据或手动删除。
- 官方支持:
chrome.storage.local是Chrome扩展的标准API,兼容性好,无需依赖第三方工具。
内容的提问来源于stack exchange,提问作者DoidArthas
相关产品推荐
相关产品推荐

