Skip to content Skip to sidebar Skip to footer

Send Message From Popup To Content Script?

Suppose I want to run a content script when I click a button in the popup page in a google chrome extension? I have tried the following: //popup.js document.addEventListener('DOMCo

Solution 1:

Have you given permissions for tabs in manifest.json as shown here.

 "permissions": [
    "tabs"
  ],

Moreover tab.id which the following code returns is of popup view (NOT A CONTENT SCRIPT TAB.ID)

chrome.tabs.getCurrent(
        function(tab){
            console.log(tab);
            chrome.tabs.sendMessage(tab.id, "doSomething");     
        }
    ); 

If you want to send message to tab you are browsing use following code's tab.id, it gives correct results

chrome.tabs.query({"status":"complete","windowId":chrome.windows.WINDOW_ID_CURRENT,"active":true}, function(tabs){
     console.log(JSON.stringify(tabs[0]));
     console.log(tabs[0].id); 
});

Let me know if you need more information


Solution 2:

The answer provided by @Sudarshan is valid and works fine, but I just found another solution to my problem. Just thought i put it here:

function clicked() {
    chrome.tabs.executeScript(null,
      {code:"console.log('hello world');"});
}

It will inject and execute the script.


Post a Comment for "Send Message From Popup To Content Script?"