0

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

1 回答 1

3

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

背景页面

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);
});

内容脚本

chrome.extension.sendRequest({
  message: "There is a video" + videoURL},  // Change the message here as needed.
  function(response) {
  return response;
});
于 2012-04-28T14:45:11.923 回答