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.

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.

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.