Fre*_*ree 31

我认为这createHTMLNotification已被弃用,因为已经接受了答案.对于现在发生在这个线程上的任何人,这里的方法在2014年1月起作用,假设您notifications在清单中拥有权限:

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);
}
Run Code Online (Sandbox Code Playgroud)

这里的一般想法只是你会发出常规通知,然后在通知创建之后立即使用普通的JavaScript方法播放声音.当然还有其他方法可以做到并组织它,但我认为这很清楚,在大多数情况下很容易实现.


Sud*_*han 7

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

示范

的manifest.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"
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

background.js

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

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

// Then show the notification.
notification.show();
Run Code Online (Sandbox Code Playgroud)

notification.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>
Run Code Online (Sandbox Code Playgroud)

参考

  • `createHTMLNotification` has been deprecated - @Free's answer below is now the correct one. (3认同)