我一直在努力将这个manifest v2 Chrome扩展移植到manifest v3,虽然我确实通过改变manifest文件的 struct 并将background.js替换为service-worker.js来移植扩展.Chrome扩展的目录 struct 似乎可以接受,should在manifest v3中工作,但我有一个持久的问题,我无法解决.我收到一条错误信息,指出...

错误:无法建立连接.接收端不存在."

"堆栈跟踪"

"service—worker. js:14(匿名函数)"

下面是我的service-worker.js代码,把它放在上下文中.Note: source code is licensed under the Mozilla Public License, version 2.

// Listen for the extension being reloaded or re-installed
chrome.runtime.onInstalled.addListener(() => {
    // Query for all open tabs
    chrome.tabs.query({}, (tabs) => {
        tabs.forEach((tab) => {
            // Inject the content script into each open tab
            chrome.tabs.registerContentScripts(tab.id, {
                file: 'content-script.js'
            });
        });
    });
});

function sendAudioMessage(actionType, audioFile) {
    chrome.tabs.query({
        active: true,
        currentWindow: true
    }, function(tabs) {
        tabs.forEach(async (tab) => {
            console.log(tab);
            if (tab.url.startsWith("chrome")) return false;
            try {
                await chrome.tabs.sendMessage(tab.id, {
                    action: actionType
                });
            } catch (e) {
                console.error(e);
                console.trace();
            }
        });
    });
}

// *** Message Handler ***
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log(message, sender, sendResponse);
    switch (message.action) {
        case 'playNavigationSound':
            sendAudioMessage('playNavigationSound');
            break;
        case 'playDownloadCompleteSound':
            sendAudioMessage('playDownloadCompleteSound');
            break;
        case 'playDownloadErrorSound':
            sendAudioMessage('playDownloadErrorSound');
            break;
        case 'playMuteWarningSound':
            sendAudioMessage('playMuteWarningSound');
            break;
        case 'changeVolume':
            changeVolume(0.75);
            break;
        default:
            console.log('Unknown message action:', message.action);
    }
});

此外,以下是我对上下文的content-script.js个代码.

// Helper function to play audio
function playAudio(audioFile) {
    console.log(audioFile, chrome.runtime.getURL(audioFile));
    const audio = new Audio(chrome.runtime.getURL(audioFile));
    // Play the audio only when the EventListener for click is triggered
    audio.addEventListener('click', () => {
        audio.play();
    });
  }
  
  // Helper function for setting volume
  function setAudioVolume(volumeLevel) {
    const audioElements = document.querySelectorAll('audio');
    audioElements.forEach(audio => {
      audio.volume = volumeLevel;
    });
  }
  
  // Receive messages from your service worker
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log(message, sender, sendResponse);
    switch (message.action) {
      case 'playNavigationSound':
        playAudio('nav.ogg');
        break;
      case 'playDownloadCompleteSound':
        playAudio('complete.ogg');
        break;
      case 'playDownloadErrorSound':
        playAudio('error.ogg');
        break;
      case 'playMuteWarningSound':
        playAudio('unlock.ogg');
        break;
      case 'changeVolume':
        setAudioVolume(message.volume);
        break;
      default:
        console.log('Unknown message action:', message.action);
    }
  });

最后,这是我的manifest.json个文件.

{
  "manifest_version": 3,
  "name": "PopupSound",
  "description": "Plays a click sound when you click on a link. Also plays a trumpet sound when you finish downloading a file.",
  "author": "Michael Gunter",
  "version": "3.0",
  "offline_enabled": true,
  "default_locale": "en",
  "icons": {
    "46": "icon_46.png",
    "96": "icon_96.png",
    "128": "icon_128.png"
  },
  "background": {
      "service_worker": "service-worker.js"
  },
  "content_scripts": [{
      "matches": ["<all_urls>"],
      "js": ["content-script.js"],
      "run_at": "document_end"
  }],
  "web_accessible_resources": [{
      "resources": [
          "*.ogg"
      ],
      "matches": [
          "<all_urls>"
      ],
      "extensions": []
  }],
  "permissions": [
      "webNavigation",
      "downloads",
      "tabs",
      "activeTab"
  ],
  "host_permissions": ["<all_urls>"],
  "content_security_policy": {}
}

我差一点就能让程序正常工作了,但这个问题让我感到困惑.如果您能帮忙,我将不胜感激.拜托了,谢谢你.

我try 使用Chrome DevTools进行调试,但无法解决问题.

推荐答案

这里有一种方法来建立消息传递给所有标签,其中URL不是以"chrome"开头.

我们在回复之前等待内容脚本的消息.

Content-script.js

// Receive messages from your service worker
console.log("Content script");
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log(message);
});

chrome.runtime.sendMessage({ url: location.href, title: document.title });

在这里,当我们重新加载扩展时,我们将重新加载所有不以"chrome"开头的选项卡.

service-worker.js

chrome.runtime.onInstalled.addListener(async (reason) => {
  console.log(reason);
  const tabs = await chrome.tabs.query({});
  for (const tab of tabs) {
    if (tab.url.startsWith("chrome")) {
      continue;
    }
    await chrome.tabs.reload(tab.id);
  }
});

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  // console.log("onUpdated", tabId, changeInfo, tab);
});

chrome.tabs.onCreated.addListener((tab) => {
  // console.log("onCreated", tab);
});

chrome.runtime.onMessage.addListener(async (message, sender) => {
  console.log(message);
  await chrome.tabs.sendMessage(sender.tab.id, "Message from ServiceWorker");
});

Javascript相关问答推荐

微软Edge编辑和重新发送未显示""

React 17与React 18中的不同setState行为

浮动Div的淡出模糊效果

D3 Scale在v6中工作,但在v7中不工作

处理时间和字符串时MySQL表中显示的日期无效

将旋转的矩形zoom 到覆盖它所需的最小尺寸&S容器

JS—删除对象数组中对象的子对象

我正在建立一个基于文本的游戏在react ,我是从JS转换.我怎样才能使变量变呢?

如何在ASP.NET JavaScript中使用Google Charts API仅对绘制为负方向的条形图移动堆叠条形图标签位置

使用getBorbingClientRect()更改绝对元素位置

更新Redux存储中的对象数组

无法读取未定义的属性(正在读取合并)-react RTK

无法重定向到Next.js中的动态URL

如何使用画布在另一个内部绘制一个较小但相同的形状,同时保持恒定的边界厚度?

如何使用puppeteer操作所有选项

React数组查找不读取变量

输入数据覆盖JSON文件

在对象的嵌套数组中添加两个属性

如何从Reaction-Redux中来自API调用的数据中筛选值

错误400:当我试图在React中使用put方法时,该字段是必需的