Chrome扩展程序:“Chrome.runtime.sendMessage”不工作

pkln4tw6  于 2024-01-04  发布在  Go
关注(0)|答案(1)|浏览(446)

我目前正在开发一个Chrome扩展程序,如果它在页面的HTML中找到特定的单词,它将关闭我当前打开的标签页。

我的content.js脚本将在打开的标签页的HTML中找到禁用的单词(如果有的话),然后运行以下代码:chrome.runtime.sendMessage({request: "closeTab" })
我的background.js脚本应该会收到以下消息:chrome.runtime.onMessage.addListener(function closeTab(request, sender, sendResponse) {if (request == "closeTab") {//code});
我的content.js脚本中的所有代码都运行正常,并正在发送该消息。尽管如此,background.js不会做任何事情。如果有人能告诉我原因,我将非常感激。

  • 编辑:我不再有之前显示的错误消息。但background.js文件中的代码仍然没有运行。
  • 编辑:为了帮助我采取了控制台的屏幕截图,它看起来像什么. Screenshot of Console
  • 以防万一我留下密码 *
    内容.js
  1. // content.js
  2. const forbiddenText = "cheese";
  3. //Program that looks for forbidden text
  4. function checkForForbiddenText() {
  5. console.log("Checking for Forbidden Text.....");
  6. const bodyText = document.body.innerText;
  7. if (bodyText.includes(forbiddenText)) {
  8. console.log("Forbidden text found! Closing the tab...");
  9. chrome.runtime.sendMessage("closeTab")};
  10. console.log(chrome.runtime.sendMessage("closeTab"));
  11. }
  12. // Run the checkForForbiddenText function when the page is fully loaded
  13. window.addEventListener("load", checkForForbiddenText);

字符串

  1. // background.js
  2. chrome.runtime.onMessage.addListener(function closeTab(request, sender, sendResponse) {
  3. if (request.from === "closeTab") {
  4. // Close the current tab
  5. console.log("Background Running.....");
  6. chrome.tabs.remove(sender.tab.id)
  7. console.log("Tab closed");
  8. }
  9. });
  10. chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
  11. // Add any other logic you need for tab updates
  12. console.log("Tab updated:", changeInfo);
  13. });

manifest.json

  1. {
  2. "manifest_version": 3,
  3. "name": "Test Blocker",
  4. "version": "1",
  5. "permissions": [
  6. "tabs",
  7. "activeTab"
  8. ],
  9. "background": {
  10. "service_worker": "background.js"
  11. },
  12. "content_scripts": [
  13. {
  14. "matches": ["<all_urls>"],
  15. "js": ["content.js"]
  16. }


] }的情况

kgqe7b3p

kgqe7b3p1#

  1. Change:
  2. chrome.runtime.sendMessage("closeTab")};
  3. to:
  4. chrome.runtime.sendMessage({action:"closeTab"});
  5. Change:
  6. if (request.from === "closeTab") {
  7. to:
  8. if (request.action == "closeTab") {

字符串
同时检查content.js中的右括号.

相关问题