Chrome扩展程序后台文件的问题

problem with Chrome extension background file

提问人:olamundo97 提问时间:9/20/2023 最后编辑:olamundo97 更新时间:9/20/2023 访问量:45

问:

{
    "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"
    }
  
  }
  

我正在尝试制作一个谷歌扩展程序来捕获来自不同网站的英语单词,但是,当我右键单击上下文菜单并尝试将这个词添加到我的扩展程序中时,没有发生任何事情。例如,当检查视图处于“非活动”状态时,用户单击我的扩展图标以弹出信息,它永远不会显示任何内容。我必须单击控制台页面并单击顶部扩展,或者将其更改为后台扩展(这是我的扩展)以使其处于活动状态。我怎样才能让它一直以活跃的心情行动?enter image description here enter image description here

我应该怎么做才能解决它?

//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>
javascript html dom google-chrome-extension chrome-extension-manifest-v3

评论

0赞 AlgoPro 9/20/2023
也请分享您的manifest.json配置。
0赞 AlgoPro 9/20/2023
您是否在manifest.json中添加了以下内容?“background”: { “scripts”: [“background.js”], “persistent”: false // 或 true, depending on your need },
0赞 olamundo97 9/20/2023
哦,对不起!我忘了分享我的manifest.json文件。我尝试像这样添加“background”: { “service_worker”: “background.js”, “persistent”: true } 但显然 manifest v3 不接受“persistent”,因为它给出了一个错误,我什至无法运行扩展
0赞 wOxxOm 9/21/2023
问题是弹出窗口在未显示时不会运行,因此无法接收消息。要么根本不使用 contextMenu(只需单击扩展图标:示例),要么将您的 UI 作为 DOM 元素添加到网页中,而不是弹出窗口。P.S. 用于 ManifestV2。persistentscripts
0赞 olamundo97 9/21/2023
@wOxxOm你能给我举个例子来说明你想说什么吗?

答: 暂无答案