-1

I have problem with sending response in chrome.notifications.onClicked.addListener.

content_scripts

chrome.runtime.sendMessage({action:'openlink', url:'http://stackoverflow.com'}, function(response) {
   console.log(response);
});

background

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
   if(request && request.action === 'openlink') {
      chrome.notifications.create('MyUniqueID',{
         type: 'basic',
         title: 'Open link',
         message: request.url,
         iconUrl: 'icon.jpg'
      });
      chrome.notifications.onClicked.addListener(function('MyUniqueID') {
         sendResponse({action:'notification-clicked'}); // <--- This
         chrome.tabs.create({url:request.url});
      });
   }
});

So I was wondering what I did wrong ?

l2aelba
  • 21,591
  • 22
  • 102
  • 138

2 Answers2

0

The sendResponse must be used immediately after received the message as a way to reply to the sender: ok I received your message and it's OK, so you continue with your code.

When you need to send a message like in your situation you need to call again the function:

chrome.tabs.sendMessage

This means to have the chrome.runtime.onMessage.addListener in the background and content.

For reference see: Chrome Extension Message Passing

gaetanoM
  • 41,594
  • 6
  • 42
  • 61
0

Nah, Just add return true after

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
   if(request && request.action === 'openlink') {
      chrome.notifications.create('MyUniqueID',{
         type: 'basic',
         title: 'Open link',
         message: request.url,
         iconUrl: 'icon.jpg'
      });
      chrome.notifications.onClicked.addListener(function('MyUniqueID') {
         sendResponse({action:'notification-clicked'}); // <--- This
         chrome.tabs.create({url:request.url});
      });
      return true;
   }
});
l2aelba
  • 21,591
  • 22
  • 102
  • 138