Daniel
Daniel

Reputation: 4342

Send one Chrome Extension desktop notification at a time

I am still learning how to create Chrome extensions, but my issue is with the desktop notifications. I am able to trigger the notifications, but when that happens for example I trigger desktop notification for content script 1. The desktop notification also triggers for content script 2. How do I make it so that they do not trigger at the same time, and only when they are called?

Background page

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

Content Script 1

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

Content Script 2

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

Upvotes: 0

Views: 1095

Answers (1)

abraham
abraham

Reputation: 47833

You can simplify the code to only use one onRequest listener and then it will stop displaying duplicate notifications.

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

Upvotes: 3

Related Questions