javascript - `chrome.scripting` 在 Manifest v3 中未定義
我正在建立一個跨瀏覽器的擴充功能,當我嘗試將擴充功能從 Firefox(manifest v2)遷移到 Chrome(manifest v3)時,一切似乎都壞掉了。
在我的擴充功能中,我需要獲取網頁在 JavaScript 中注入的變數。我最初的解決方案是直接注入一個包含我的 js 代碼的 <script /> 標籤,這在 Firefox 中運行良好。但在 Chrome 中,可能因為該網站的嚴格 CSP 政策,我無法再注入腳本。
我還找到這個 StackOverflow 的答案,說明如何在內容腳本中獲取頁面變數。但在嘗試這個解決方案時,我遇到了另一個錯誤:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'executeScript')
我使用的程式碼是直接從答案中複製的:
export const getPageVar = async (name: string, tabId?: number) => {
const [{ result }] = await browser.scripting.executeScript({
func: (name) => console.log(name),
args: [name],
target: {
tabId:
tabId ??
(
await browser.tabs.query({ active: true, currentWindow: true })
)[0].id,
},
});
return result;
};
然後我就這樣叫它:
// ...
const result = await getPageVar("_feInstance");
這是我的 manifest.json:
{
"name": "Luogu Improved",
"version": "0.0.1",
"description": "Improve Luogu to a new level.",
"homepage_url": "https://github.com/samzhangjy/luogu-improved",
"manifest_version": 3,
"icons": {
"192": "../../../icons/icon-192.png"
},
"permissions": [
"activeTab",
"storage",
"tabs",
"scripting",
"declarativeContent"
],
"host_permissions": [
"https://www.luogu.com.cn/*"
],
"content_scripts": [
{
"matches": [
"https://www.luogu.com.cn/*"
],
"js": [
"../src/plugins.ts"
]
}
],
"background": {
"service_worker": "../src/index.ts",
"type": "module"
},
"action": {
"default_icon": "../../../icons/icon-32.png",
"default_title": "Luogu Improved",
"default_popup": "../../lim-launch-page/dist/index.html"
}
}
順便說一下,除了上述的錯誤之外,我還有另一個錯誤,但即使有這個錯誤,其餘的程式碼似乎運行正常:
Uncaught TypeError: Cannot read properties of undefined (reading 'onActivated')
而我的程式碼大概是這樣的:
browser.tabs.onActivated.addListener(() => registerPlugins(defaultPlugins));
browser.tabs.onUpdated.addListener(() => registerPlugins(defaultPlugins));
browser.tabs.onHighlighted.addListener(() => registerPlugins(defaultPlugins));
我已經為這件事掙扎了兩天,完全沒頭緒... 先謝謝你了!!
編輯:我在我的程式碼中使用 webextension-polyfill。我這樣匯入它:
import * as browser from "webextension-polyfill";