Saturday, 31 August 2019

send message from content script to background script in chrome extension

send message from Content script to background script in chrome extension

You really need this to create chrome extensions for websites like amazon, facebook, flipkart 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.

chrome.runtime.sendMessage({'type': 'fromcontent'});

Step 3: Add this code to background.js file

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {  
    if (request.type == 'fromcontent') {
               ///////// do your work here
           }
});

In this way we can send messages.
Thanks for reading.

No comments:

Post a Comment