Chrome扩展问题:选中文字旁图标无法正常显示求助
问题修复方案
核心原因
你遇到的chrome-extension://invalid/ net::ERR_FAILED错误,是因为Manifest V3中扩展内资源默认无法被内容脚本直接访问,必须在manifest.json里显式声明允许访问的资源路径。
步骤1:更新manifest.json
添加web_accessible_resources字段,授权内容脚本访问图标资源:
{ "manifest_version": 3, "name": "Addons", "version": "1.0", "description": "Describe Addons", "permissions": [ "storage", "activeTab", "notifications", "tabs" ], "action": { "default_icon": "icons/icon.png" }, "icons": { "48": "icons/icon.png" }, "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content.js"] } ], "web_accessible_resources": [ { "resources": ["icons/icon.png"], "matches": ["<all_urls>"] } ], "content_security_policy": { "extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self';" } }
步骤2:优化content.js逻辑(可选但推荐)
解决重复创建图标、传递搜索文本等问题:
document.addEventListener('mouseup', function (event) { // 移除已存在的图标,避免重复创建 const existingIcon = document.getElementById('extensionIcon'); if (existingIcon) { document.body.removeChild(existingIcon); } const selectedText = window.getSelection().toString().trim(); if (selectedText === '') return; const icon = new Image(); const iconUrl = chrome.runtime.getURL('icons/icon.png'); icon.src = iconUrl; icon.id = 'extensionIcon'; icon.style.position = 'absolute'; icon.style.cursor = 'pointer'; icon.style.zIndex = '9999'; // 确保图标在页面最上层 const range = window.getSelection().getRangeAt(0); const rect = range.getBoundingClientRect(); // 调整位置,避免遮挡选中文字 icon.style.top = `${rect.top + window.scrollY - icon.height / 2}px`; icon.style.left = `${rect.right + window.scrollX + 10}px`; document.body.appendChild(icon); icon.addEventListener('click', function (e) { e.preventDefault(); // 打开搜索引擎新标签页,填入选中文字(示例用Google,可替换为百度等) const searchUrl = `https://www.google.com/search?q=${encodeURIComponent(selectedText)}`; window.open(searchUrl, '_blank'); document.body.removeChild(icon); }); });
注意事项
- 修改manifest后,需在Chrome扩展管理页面点击「重新加载」生效
- 若使用其他搜索引擎,替换
searchUrl中的地址即可(如百度:https://www.baidu.com/s?wd=${encodeURIComponent(selectedText)})
内容的提问来源于stack exchange,提问作者Giggest
相关产品推荐
相关产品推荐

