![](/img/trans.png)
[英]Inject javascript from content script with a chrome extension v3
[英]How to load content script in chrome extension v3
我正在将我的 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.
这是我的清单:
{
"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
}
]
}
如果我在这里走的是正确的道路,那么我的清单中肯定缺少一些东西。 有什么建议么?
尝试以下方法:-
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.