I'm building a cross-browser extension and when I tried to migrate the extension from Firefox (manifest v2) to Chrome (manifest v3), everything seems to broke.
In my extension I need to get a variable injected by the webpage in JavaScript. My original solution was to directly inject a <script />
tag with my js code inside and it worked fine in Firefox. But in Chrome maybe because of this site's strict CSP policy, I can no longer inject scripts.
And I found this StackOverflow answer about how to fetch page variables in content script. But while trying this solution I encountered another error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'executeScript')
The code I used was directly copied from the answer:
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;
};
And I called it like:
// ...
const result = await getPageVar("_feInstance");
Here is my 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"
}
}
And btw, I have another error other than the above one but the rest of the code seemed to be working fine even with the error:
Uncaught TypeError: Cannot read properties of undefined (reading 'onActivated')
And my code is something like:
browser.tabs.onActivated.addListener(() => registerPlugins(defaultPlugins));
browser.tabs.onUpdated.addListener(() => registerPlugins(defaultPlugins));
browser.tabs.onHighlighted.addListener(() => registerPlugins(defaultPlugins));
I've been struggling with this for two days and didn't have a clue... Thanks in advance!!
EDIT: I'm using webextension-polyfill
in my code. I import it like:
import * as browser from "webextension-polyfill";