简体   繁体   中英

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('DOMContentLoaded', function () {
  document.querySelector('button').addEventListener('click', clicked);
  main();
});

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

And in the content script:

chrome.extension.onMessage.addListener(
    function(message, sender, sendResponse){
        console.log("hello world");
    }
);

The problem is that the tab in the callback from chrome.tabs.getCurrent( ) is undefined.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM