提问人:olamundo97 提问时间:9/20/2023 最后编辑:olamundo97 更新时间:9/20/2023 访问量:45
Chrome扩展程序后台文件的问题
problem with Chrome extension background file
问:
{
"manifest_version": 3,
"name": "Inglesando 😎 - The Word Catcher",
"version": "1.0",
"description": "Amplie o seu vocabulário capturarando palavras em inglês como se tivesse capturando pokémons.",
"permissions": ["contextMenus", "storage"],
"action": {
"default_popup": "popup.html"
},
"background": {
"service_worker": "background.js",
"persistent": true
},
"icons": {
"16": "images/flag.png"
}
}
我正在尝试制作一个谷歌扩展程序来捕获来自不同网站的英语单词,但是,当我右键单击上下文菜单并尝试将这个词添加到我的扩展程序中时,没有发生任何事情。例如,当检查视图处于“非活动”状态时,用户单击我的扩展图标以弹出信息,它永远不会显示任何内容。我必须单击控制台页面并单击顶部扩展,或者将其更改为后台扩展(这是我的扩展)以使其处于活动状态。我怎样才能让它一直以活跃的心情行动?
我应该怎么做才能解决它?
//popup.js file
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
let text = request.text;
// Check if the message contains the 'text' property
try {
if (text !== undefined) {
const wordOfList = document.getElementById("wordList");
if (!wordOfList) return;
const list = document.createElement('li');
// Increment a counter for each word
if (!wordOfList.dataset.counter) {
wordOfList.dataset.counter = 1;
} else {
wordOfList.dataset.counter++;
}
// Concatenate the counter with the text content
list.textContent = wordOfList.dataset.counter + ' - ' + text;
wordOfList.appendChild(list);
}
} catch (err) {
console.log(err);
}
});
//background.js
chrome.contextMenus.onClicked.addListener(genericOnClick); //It listens for clicks on context menu items and calls the genericOnClick function when an item is clicked.
function genericOnClick(info) { //The info parameter contains information about the clicked item
// Standard context menu item function
let text = info.selectionText;
console.log(`Selected text: ${text}`);
// Send the words for the popup
chrome.runtime.sendMessage({ text });
};
// This event is triggered when the extension is installed or updated.
chrome.runtime.onInstalled.addListener(function () {
// Create one test item for each context type.
let contexts = [
'page',
'selection',
'link',
'editable',
'image',
'video',
'audio'
];
for (let i = 0; i < contexts.length; i++) {
let context = contexts[i];
let title = "Inglesando 😎 - Add word";
chrome.contextMenus.create({
title: title,
contexts: [context],
id: context,
});
}
});
<!-- popup.html -->
<!DOCTYPE html>
<html>
<head>
<title>Inglesando 😎 - The Word Catcher</title>
<link rel="stylesheet" href="popup.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>
<div class="content">
<h3>Adicione novas palavras</h2>
<img src="./images/extension-icon.png" id="iconImage">
</div>
<p>Suas palavras:</p>
<ul id="wordList"></ul>
<script src="popup.js"></script>
</html>
答: 暂无答案
评论
persistent
scripts