我正在学习 Javascript,我以为我可以做一个小项目,但我有很多错误,我不知道我的代码出了什么问题。我正在尝试制作一个 chrome 扩展,将注音假名添加到日语文本中,为此我使用 Kuroshiro 库。
我相信我安装它是正确的,并且当我在本地运行它时它可以工作。但是当我将其作为扩展上传时,它似乎不起作用。这是我的manifest.json,
{
"manifest_version": 3,
"name": "Hello Extensions",
"description": "Base Level Extension",
"version": "1.0",
"action": {
"default_popup": "popup.html",
"default_icon": "hello_extensions.png"
},
"permissions": ["activeTab", "scripting"],
"web_accessible_resources": [
{
"resources": [
"lib/kuroshiro.min.js","lib/kuroshiro-analyzer-kuromoji.min.js","add_furigana.js","content3.js","dict/*"
],
"matches": [
"<all_urls>"
]
}
],
"content_scripts": [
{
"js": [
"content3.js"
],
"matches": [
"<all_urls>"
]
}
]
}
这是我的 content3.js,
// Function to inject Kuroshiro and its dependencies into the web page
function injectKuroshiro() {
// Create script elements for Kuroshiro and its dependencies
const kuroshiroScript = document.createElement('script');
kuroshiroScript.src = chrome.runtime.getURL('lib/kuroshiro.min.js');
kuroshiroScript.onload = function() {
const analyzerScript = document.createElement('script');
analyzerScript.src = chrome.runtime.getURL('lib/kuroshiro-analyzer-kuromoji.min.js');
analyzerScript.onload = function() {
const add_furiganaScript = document.createElement('script');
add_furiganaScript.src = chrome.runtime.getURL('add_furigana.js');
document.head.appendChild(add_furiganaScript);
};
document.head.appendChild(analyzerScript);
};
document.head.appendChild(kuroshiroScript);
}
injectKuroshiro();
和 add_furigana.js,
async function initializeKuroshiro() {
const kuroshiro = new Kuroshiro();
try {
// Initialize Kuroshiro with the Kuromoji analyzer
const dictPath = chrome.runtime.getURL('dict/'); // Assuming 'dict' is your folder name
await kuroshiro.init(new KuromojiAnalyzer({ dicPath: dictPath }));
// Convert the given text to hiragana
const result = await kuroshiro.convert("感じ取れたら手を繋ごう、重なるのは人生のライン and レミリア最高!", { to: "hiragana" });
// Output the converted text
console.log(result);
} catch (err) {
console.error("Kuroshiro initialization failed:", err);
}
}
initializeKuroshiro();
它给了我这个错误,
如果我删除 dictPath 我会得到这个错误
我确信我有正确的字典文件,但我不知道是什么原因导致的,而且 chatgpt 根本没有帮助。
奇怪的是它在 popup.html 中工作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="lib/kuroshiro.min.js"></script>
<script src="lib/kuroshiro-analyzer-kuromoji.min.js"></script>
<script src="add_furigana.js"></script>
</head>
<body>
</body>
</html>
抱歉,如果这是一个愚蠢的问题,但我在这里错过了什么?
删除 content3.js 并加载 kuroshiro.min.js、kuroshiro-analyzer-kuromoji.min.js 和 add_furigana.js 作为内容脚本。
"web_accessible_resources": [
{
"resources": [
"dict/*"
],
"matches": [
"<all_urls>"
]
}
],
"content_scripts": [
{
"js": [
"lib/kuroshiro.min.js",
"lib/kuroshiro-analyzer-kuromoji.min.js",
"add_furigana.js"
],
"matches": [
"<all_urls>"
]
}
]