我想使用 Chrome 扩展程序(仅供我自己使用)监视网页上动态变化的值,并在该值变化时播放通知声音并显示警报。此页面不一定位于事件选项卡中。
到目前为止,我有以下代码,我唯一需要做的就是在值更改时触发 background.js。我的问题是如何做到这一点。
manifest.json
{
"manifest_version": 2,
"name": "Example Website Notifications",
"description": "Displays notifications on Example Website.",
"version": "1.0",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [{
"matches": ["https://www.example.com/*"],
"js": ["jquery.js", "content.js"]
}]
}
content.js
var value = $('#element').html();
window.setInterval(function() {
var newValue = $('#element').html();
if (newValue != value) {
/* Run code in background.js */
value = newValue;
}
}, 5000);
我以 5 秒的间隔检查该值。如果有一种方法可以“知道”值何时发生变化,而不是每 5 秒检查一次,我也对此持开放态度。
背景.js
var sound = new Audio('sound.mp3').play();
alert('Value Changed');
除了声音通知之外,我还有 alert() 的原因是,浏览器窗口图标会在任务栏中闪烁,以防我错过听到声音警报。
当我测试background.js以查看音频是否播放时,首先显示警报,然后在单击警报上的“确定”后播放音频,即使播放音频文件的行位于前面。有什么想法为什么会发生这种情况吗?
最佳答案
要将事件传达给后台页面,您可以使用 Messaging 。
示例(为了可扩展而稍微过度设计):
// content.js
chrome.runtime.sendMessage({type: "alertUser"});
// background.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
switch(message.type) {
case "alertUser":
/* play sound, draw attention */
break;
}
});
请注意,您不必使用可怕的警报
来引起注意。有 windows
API 可以做到这一点:
// Assuming you have `sender` from the messaging API
// This will make the window blink/draw attention in the taskbar or equivalent
chrome.windows.update(sender.tab.windowId, {drawAttention: true});
// Optionally, switch to the tab inside the window as well
chrome.tabs.update(sender.tab.id, {active: true});
alert
应该被认为是有害的:它会暂停 JS 执行直到被解除,这解释了您所经历的效果(延迟播放)。应该避免这种情况。
另一种以视觉方式通知用户的“有机”方法是使用 notification
API 的 toast 样式通知。它比浏览器图标闪烁要明确得多。
If there is a way to "know" when the value change happens, instead of checking every 5s, I am also open to that.
是的;主要是使用名为 Mutation Observers 的工具。请参阅有关该主题的 this canonical question。
关于javascript - Chrome 扩展程序 : Play a notification sound when a web page element content changes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46321885/