一次发送一个Chrome扩展程序桌面通知

时间:2012-04-28 13:40:13

标签: google-chrome-extension

我仍在学习如何制作Chrome扩展程序,但问题在于桌面通知。我能够触发通知,但是当发生这种情况时,我会触发内容脚本的桌面通知1.桌面通知也会触发内容脚本2.我如何制作它以便它们不会同时触发,以及只有当他们被召唤?

背景页

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    // Create a simple text notification
    var notifyWinner = webkitNotifications.createNotification('48.png', 'Notification', request.winnerMessage);
    notifyWinner.show();
    setTimeout(function(){ notifyWinner.cancel(); },10000);
});

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    // Create a simple text notification
    var notifyVideo = webkitNotifications.createNotification('48.png', 'Notification', request.videoMessage);
    notifyVideo.show();
    setTimeout(function(){ notifyVideo.cancel(); },10000);
});

内容脚本1

chrome.extension.sendRequest({winnerMessage: "You won!!!"}, function(response) {
                return response;
            });

内容脚本2

chrome.extension.sendRequest({videoMessage: "There is a video" + videoURL}, function(response) {
                      return response;
                  });

1 个答案:

答案 0 :(得分:3)

您可以简化代码以仅使用一个onRequest侦听器,然后它将停止显示重复的通知。

BACKGROUND_PAGE

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    // Create a simple text notification
    var notify = webkitNotifications.createNotification('48.png', 'Notification', request.message);
    notify.show();
    setTimeout(function(){ notify.cancel(); },10000);
});

content_script

chrome.extension.sendRequest({
  message: "There is a video" + videoURL},  // Change the message here as needed.
  function(response) {
  return response;
});