我正在尝试创建一个 Chrome 扩展程序,它将在网页中嵌入 CodeMirror 编辑器。我使用 vite 捆绑 CodeMirror 包并使用
chrome.scripting.executeScript
运行我的 javascript 文件。
manifest.json
{
"manifest_version": 3,
"name": "Odoo Better Ide",
"description": "Better Ide",
"version": "1.0",
"icons": {
"16": "images/icon-16.png",
"32": "images/icon-32.png",
"48": "images/icon-48.png",
"128": "images/icon-128.png"
},
"background": {
"service_worker": "src/background.js",
"type": "module"
},
"action": {
"default_icon": {
"16": "images/icon-16.png",
"32": "images/icon-32.png",
"48": "images/icon-48.png",
"128": "images/icon-128.png"
}
},
"permissions": ["activeTab", "scripting"]
}
background.js(用于我的服务人员并检查用户是否单击扩展图标)
chrome.runtime.onInstalled.addListener(() => {
chrome.action.setBadgeText({
text: "OFF",
});
});
const odooUrl = "https://demo";
chrome.action.onClicked.addListener(async (tab) => {
if (tab.url.startsWith(odooUrl)) {
const prevState = await chrome.action.getBadgeText({ tabId: tab.id });
const nextState = prevState === "ON" ? "OFF" : "ON";
await chrome.action.setBadgeText({
tabId: tab.id,
text: nextState,
});
if (nextState === "ON") {
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ["/dist/content-script.bundle.js"], // this is the bundled js file
});
} else if (nextState === "OFF") {
console.log("Turned off");
}
}
});
content-script.js(将通过 vite rollup 捆绑)
import { EditorView, basicSetup } from "codemirror";
import { python } from "@codemirror/lang-python";
const ideElem = document.querySelector(".o_field_code");
console.log(ideElem);
if (ideElem) {
console.log(ideElem);
const editorElem = initiazeEditorView(ideElem);
console.log(editorElem);
}
function initiazeEditorView(ideElem) {
let editor = new EditorView({
extensions: [basicSetup, python()],
parent: ideElem,
});
return editor;
}
vite.config.js
import { defineConfig } from "vite";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import terser from "@rollup/plugin-terser";
export default defineConfig({
build: {
rollupOptions: {
input: "src/content-script.js",
output: {
dir: "dist",
entryFileNames: "content-script.bundle.js",
format: "iife",
},
plugins: [nodeResolve(), terser()],
},
},
});
扩展程序工作正常,但每次我尝试运行(单击扩展程序图标)并执行代码时:
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ["/dist/content-script.bundle.js"], // this is the bundled js file
});
它总是显示错误
Uncaught (in promise) Error: Could not load file '/dist/content-script.bundle.js'. It isn't UTF-8 encoded.
当我在 VSCode 中打开捆绑文件时,它显示它是“UTF-8”。我也尝试了 VSCode 的
Save with encoding
功能,但仍然没有成功。
如果您想克隆存储库,请点击以下链接:https://github.com/dwarjie/odoo-better-ide
使用十六进制编辑器检查文件。 允许的 UTF 字符有:
0xxxxxxx
or
110xxxxx 10xxxxxx
or
1110xxxx 10xxxxxx 10xxxxxx
or
11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
--例如,0xF8 = 11111000 是不允许的。
此外,您可能需要包含 BOM 字符(字节顺序标记)= 0x EF BB BF,它是一个标记,用于指示字节顺序是小端(存储在较大内存地址中的最高有效字节)还是大端endian(存储在较小内存地址中的最高有效字节),特别是当旧系统需要将文件显式识别为 UTF-8 时。
但是为了与 unix/linux 环境进行互操作,可能需要省略 BOM。