我一直致力于将此清单 v2 Chrome 扩展移植到清单 V3,同时我通过更改清单文件中的结构并将
background.js
替换为 service-worker.js
来移植该扩展。 Chrome 扩展的目录结构似乎可以接受,并且 应该 在清单 v3 中工作,但我有一个无法解决的持续问题。当我在 Google Chrome 中运行扩展程序时,我不再出现语法错误,但是,当我希望播放音频时,不会播放任何音频。
这是我的
service-worker.js
代码,将其放入上下文中。 注意:源代码已获得 Mozilla 公共许可证版本 2 的许可。
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((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(message.volume);
break;
case 'webNavigationEvent':
handleWebNavigationEvent(message.event);
break;
default:
console.log('Unknown message action:', message.action);
}
});
function handleWebNavigationEvent(event) {
switch (event.type) {
case 'beforeNavigate':
console.log('Before navigate: ', event.details);
// Handle the event here
break;
case 'committed':
console.log('Committed: ', event.details);
// Handle the event here
break;
case 'DOMContentLoaded':
console.log('DOM content loaded: ', event.details);
// Handle the event here
break;
case 'completed':
console.log('Navigation completed: ', event.details);
// Handle the event here
break;
case 'errorOccurred':
console.log('Error occurred: ', event.details);
// Handle the event here
break;
default:
console.log('Unknown webNavigation event type:', event.type);
}
}
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
上下文代码。
// 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
});
// 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;
});
}
function setupWebNavigationListeners() {
chrome.webNavigation.onBeforeNavigate.addListener((details) => {
console.log('Before navigate: ', details);
chrome.runtime.sendMessage({
action: 'webNavigationEvent',
event: {
type: 'beforeNavigate',
details: details
}
});
});
chrome.webNavigation.onCommitted.addListener((details) => {
console.log('Committed: ', details);
chrome.runtime.sendMessage({
action: 'webNavigationEvent',
event: {
type: 'committed',
details: details
}
});
});
chrome.webNavigation.onDOMContentLoaded.addListener((details) => {
console.log('DOM content loaded: ', details);
chrome.runtime.sendMessage({
action: 'webNavigationEvent',
event: {
type: 'DOMContentLoaded',
details: details
}
});
});
chrome.webNavigation.onCompleted.addListener((details) => {
console.log('Navigation completed: ', details);
chrome.runtime.sendMessage({
action: 'webNavigationEvent',
event: {
type: 'completed',
details: details
}
});
});
chrome.webNavigation.onErrorOccurred.addListener((details) => {
console.log('Error occurred: ', details);
chrome.runtime.sendMessage({
action: 'webNavigationEvent',
event: {
type: 'errorOccurred',
details: details
}
});
});
}
setTimeout(setupWebNavigationListeners, 650); // Delay of 650 milliseconds
// 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);
}
});
// You are going to have to deal with those `webNavigation` events.
最后,这是我的
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": {
"48": "icon_48.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": {}
}
我已经非常接近让程序正常运行,但没有音频播放的问题让我感到困惑。 注意:我将音频文件放置在与我的存储库相同的目录中,因此损坏的链接/路径不是问题。 我将非常感谢您的帮助。请并谢谢你。
我尝试在 StackOverflow 上研究其他问题,但我感到困惑和困惑。我非常感谢您对这个问题的帮助。谢谢你。
audio.play()
。这个要求看起来很奇怪,所以你可能应该删除点击侦听器并立即调用 audio.play()
。chrome
API。