我找不到任何现成的解决方案,尤其是新的 Manifest V3
background
service-worker
架构。
我需要创建一个没有 HTML 的简单 Chrome 扩展,以直接运行 JS,以在单击其图标时显示带有某种 DOM 值(例如 DIV 的 ID)的警报框。但我收到这些错误:
manifest.json
{
"manifest_version": 3,
"name": "Practice",
"description": "Practice",
"version": "1.0",
"action": {
"default_icon": "practice.png"
},
"background": {
"service_worker": "background.js"
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["practice.js"],
"run_at": "document_end"
}]
}
背景.js
chrome.tabs.onUpdated.addListener(function () {
chrome.tabs.executeScript(null, { file: "practice.js" });
});
practice.js
var elem = document.getElementById("myDiv");
alert(elem ? 'found: ' + elem.id : 'not found');
background.js 中出现错误:
Uncaught ReferenceError: alert is not defined
host_permissions
(用于无人值守/自动注入)或 activeTab
权限(点击注入)。content_scripts
声明,因为它会在每次导航时而不是单击时将指定的脚本注入到每个选项卡中的每个页面中。//清单.json
{
"manifest_version": 3,
"name": "Practice",
"description": "Practice",
"version": "1.0",
"action": {
"default_popup": "popup.html",
"default_icon": "practice.png"
},
"permissions": ["activeTab", "scripting"]
}
popup.html
<p id=msg></p>
<script src=popup.js></script>
popup.js
(async () => {
const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
const [{result, err}] = await chrome.scripting.executeScript({
target: {tabId: tab.id},
injectImmediately: true,
func: id => document.getElementById(id)?.id, // result must be JSON-compatible
args: ['myDiv'],
}).catch(err => [{err: err.message}]);
document.getElementById('msg').textContent = result
? 'found: ' + result
: err || 'not found';
})();