【问题标题】:How to implement a notification popup with sound in chrome extension如何在 Chrome 扩展中实现带有声音的通知弹出窗口
【发布时间】:2013-02-01 18:36:56
【问题描述】:

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

就像Checker Plus for Gmail

【问题讨论】:

    标签: google-chrome-extension notifications


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您可以使用以下代码作为在桌面通知中播放声音的参考,它使用<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"
              ]
          }
      }
      

      background.js

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

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

      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>
      

      参考文献

      【讨论】:

      • createHTMLNotification 已被弃用 - @Free 下面的答案现在是正确的。
      猜你喜欢
      • 1970-01-01
      • 2011-09-27
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 2016-12-30
      • 2018-10-28
      相关资源
      最近更新 更多