Saturday, 31 August 2019

send message from popup to content script in chrome extension

send message from popup to content 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 popup.js file to send message to content.

  chrome.tabs.query({
                    active: true,
                    currentWindow: true
                }, function (tabs) {
                    chrome.tabs.sendMessage(tabs[0].id,{'action':'frompopup'});
                });


Step 3: Add this code to content.js file

chrome.extension.onMessage.addListener(function(message, sender, send_response) {
    if (message.action== 'frompopup') {
      ////////// do your work here
    }
});

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

No comments:

Post a Comment