声音通知 chrome 扩展,使用 Javascript

问题描述 投票:0回答:1

我试图制作一个实时扩展,每当 URL 状态栏显示在 chrome 中用于工作目的时,它就会播放声音通知,我正在作为聊天代理工作,每当弹出聊天时,没有声音通知我,它实际上有效,但是仅在任何网页启动时,例如当我输入 www.google.com 时,它会显示 URL 状态栏并触发声音,但之后当它再次出现时,例如当我单击我的帐户或我时执行任何其他操作,它不会发出任何声音,我也尝试过从网页捕获元素,但仍然不起作用 这是我的脚本:

// background.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status === 'loading') {
// Tab is in 'loading' state, play sound notification
const audio = new Audio(chrome.runtime.getURL('sound.mp3'));
audio.play();
}
});
// contentScript.js
function checkStatusBar() {
const statusBar = document.querySelector('#status');

if (statusBar) {
const statusBarText = statusBar.innerText.toLowerCase();
if (statusBarText.includes('waiting for')) {
// Status bar shows 'waiting for', play sound notification
const audio = new Audio(chrome.runtime.getURL('sound.mp3'));
audio.play();
}
}
}

setInterval(checkStatusBar, 500); // Check every 0.5 seconds for changes
{
"manifest_version": 2,
"name": "URL Status Bar Sound Notifier",
"version": "1.0",
"description": "Plays a sound when the URL status bar shows 'Waiting for...'",
"permissions": ["activeTab"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"icons": {
"16": "icon.png",
"48": "icon.png",
"128": "icon.png"
},
"manifest_version": 2
}

请我需要帮助,这对我的生计非常重要,提前感谢。

我期待每次 URL 状态栏显示时都会有声音通知

javascript json google-chrome-extension
1个回答
0
投票

像这样更新你的background.js文件

// background.js

// Function to play sound notification
function playNotificationSound() {
    const audio = new Audio(chrome.runtime.getURL('sound.mp3'));
    audio.play();
}

// Function to check if the URL status bar indicates a chat pop-up
function checkStatusBar(statusBarText) {
    if (statusBarText.includes('Waiting for')) {
        // URL status bar shows 'Waiting for', trigger sound notification
        playNotificationSound();
    }
}

// Listen for updates to the tab's URL and check the status bar
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (changeInfo.status === 'loading') {
        // Get the updated tab's URL status bar text
        chrome.tabs.executeScript(tabId, { code: 'document.querySelector("status").innerText.toLowerCase();' }, function(result) {
            if (chrome.runtime.lastError) {
                console.error(chrome.runtime.lastError.message);
            } else {
                // Check the status bar text for chat indication
                checkStatusBar(result[0]);
            }
        });
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.