20

如何在 chrome 扩展中实现带有声音的通知弹出窗口。

就像用于 Gmail 的 Checker Plus

4

2 回答 2

34

我认为createHTMLNotification自从写了接受的答案以来,这已经被弃用了。对于现在发生在此线程上的任何人,假设您notifications在清单中具有权限,这是一种自 2014 年 1 月起有效的方法:

背景.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 方法播放声音。当然还有其他方法可以做到这一点并组织它,但我认为这在大多数情况下非常清楚并且很容易实现。

于 2014-01-05T03:41:46.747 回答
7

您可以使用以下代码作为在桌面通知中播放声音的参考,它使用<audio>标签与Desktop Notifications.

示范

清单.json

使用清单文件注册通知权限和背景页面。

{
    "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"
        ]
    }
}

背景.js

从后台应用程序创建通知页面。

// create a HTML notification:
var notification = webkitNotifications.createHTMLNotification(
    'notification.html' // html url - can be relative
);

// Then show the notification.
notification.show();

通知.html

播放一些随机歌曲

<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>

参考

于 2013-02-17T07:07:05.423 回答