Friday 9 August 2019

send message from background script to content script on particular tab

send message from background script to content script on particular tab in chrome extension

You really need this to create chrome extensions for websites like amazon, flipkart, facebook etc..
Step 1: Set permissions to all tabs in manifest file of chrome extension.

"permissions": [
        "activeTab",
          "tabs"
    ],

Step 2: Add this code to contentscript.js file to send message to background.

/// content script is work individually for every tab so we can send message to background

chrome.runtime.sendMessage({'action':'content'});


Step 3: Add this code to background.js file

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {  
   var senderId = sender.tab.id; ///// sender id of particular tab
    if (request.from == 'content') {
               chrome.tabs.sendMessage(senderId,{action:'takeaction',});
           }
});

In this way we can send back message to particular tab by sending sender id.
Thanks reading.

No comments:

Post a Comment