javascript - 如何在 chrome 扩展 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;
}
推荐阅读
- c++ - 链接 C++ 项目后 CodeBlocks 无法找到 C 库(Windows、GNU GCC 编译器)
- css - 测试 VueJS 应用程序可视化端
- python - 一种有效的方法来合并超过 10 个文件,每个文件在一列上有超过百万行
- javascript - 如何通过使用 JQuery/JavaScript 单击 div 将文本从一个页面传递到另一个页面
- python - 内置操作的错误参数类型
- linux - 如何使用 perl 脚本和 ssh 在远程 linux 服务器中运行 bash 或 shell 脚本
- ruby-on-rails - 在 REST API 中返回 HTTP 422 时可以区分情况吗?
- python - 要列出的字节字符串
- angular - 获取不同语言的 Angular 错误
- c# - SendOrPostCallback 行为