【发布时间】:2013-02-01 18:36:56
【问题描述】:
如何在 chrome 扩展中实现带有声音的通知弹出窗口。
【问题讨论】:
标签: google-chrome-extension notifications
如何在 chrome 扩展中实现带有声音的通知弹出窗口。
【问题讨论】:
标签: google-chrome-extension notifications
我认为createHTMLNotification 已被弃用,因为接受的答案已被写入。对于现在发生在此线程上的任何人,假设您在清单中具有 notifications 权限,这是一种自 2014 年 1 月起有效的方法:
background.js
createNotification();
audioNotification();
function audioNotification(){
var yourSound = new Audio('yourSound.mp3');
yourSound.play();
}
function createNotification(){
var opt = {type: "basic",title: "Your Title",message: "Your message",iconUrl: "your_icon.png"}
chrome.notifications.create("notificationName",opt,function(){});
//include this line if you want to clear the notification after 5 seconds
setTimeout(function(){chrome.notifications.clear("notificationName",function(){});},5000);
}
这里的总体思路是,您将发送常规通知,然后在通知创建后立即使用普通 JavaScript 方法播放声音。当然还有其他方法可以做到这一点并组织它,但我认为这在大多数情况下非常清晰且非常容易实现。
【讨论】:
您可以使用以下代码作为在桌面通知中播放声音的参考,它使用<audio> 标签与Desktop Notifications 结合使用。
已注册通知权限和带有清单文件的后台页面。
{
"name": "Notification with Audio",
"description": "http://stackoverflow.com/questions/14917531/how-to-implement-a-notification-popup-with-sound-in-chrome-extension",
"manifest_version": 2,
"version": "1",
"permissions": [
"notifications"
],
"background": {
"scripts": [
"background.js"
]
}
}
从后台应用程序创建通知页面。
// create a HTML notification:
var notification = webkitNotifications.createHTMLNotification(
'notification.html' // html url - can be relative
);
// Then show the notification.
notification.show();
播放一些随机歌曲
<html>
<body>
<p>Some Nice Text While Playing Song.. </p>
<audio autoplay>
<source src="http://www.html5rocks.com/en/tutorials/audio/quick/test.mp3" type="audio/mpeg" />
<source src="http://www.html5rocks.com/en/tutorials/audio/quick/test.ogg" type="audio/ogg" />
</audio>
</body>
</html>
【讨论】:
createHTMLNotification 已被弃用 - @Free 下面的答案现在是正确的。