我正在将 v2 扩展迁移到 v3。现在,我不清楚的第一件事是内容脚本是如何加载到页面中的。我的实现如下(后台脚本):
chrome.action.onClicked.addListener(tab => {
chrome.windows.create({
// Just use the full URL if you need to open an external page
url: chrome.runtime.getURL("hello.html"),
type: "panel", height: 200, width:200
}, (win) => {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
const currTab = tabs[0];
if (currTab) {
chrome.scripting.executeScript({
target: {tabId: currTab.id},
files: ['/content.js'],
}, () => { });
}
});
});
});
我认为这个例子是我最好的尝试:) 因此,当我运行此代码时,我在控制台中收到以下错误:
Unchecked runtime.lastError: Cannot access contents of url "". Extension manifest must request permission to access this host.
这是我的 list :
{
"name": "Hello, World!",
"version": "1.0",
"manifest_version": 3,
"background": { "service_worker": "background.js" },
"action": {
"default_icon": {
"16": "icon16.png"
}
},
"permissions": [
"tabs",
"bookmarks",
"unlimitedStorage",
"activeTab",
"scripting"
],
"optional_permissions": [],
"host_permissions": [
"*://*/*"
],
"web_accessible_resources": [
{
"resources": ["/content.js"],
"matches": [],
"extension_ids": [],
"use_dynamic_url": true
}
]
}
如果我走的是正确的道路,那么我的 list 中一定缺少一些东西。有什么建议吗?
最佳答案
尝试以下操作:-
chrome.action.onClicked.addListener(insertScript)
async function insertScript() {
tabId = await getTabId();
chrome.scripting.executeScript({
target: {tabId: tabId}
files: ['/content.js']
})
}
async function getTabId() {
var tabs = await chrome.tabs.query({active: true, currentWindow: true});
return tabs[0].id;
}
关于javascript - 如何在 Chrome 扩展 v3 中加载内容脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67432398/