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



我仍在学习如何创建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;
                  });

您可以将代码简化为仅使用一个 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;
});

最新更新