Send message from popup to content script?

断了今生、忘了曾经 提交于 2019-12-10 16:27:06

问题


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.


回答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




回答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.



来源:https://stackoverflow.com/questions/13646389/send-message-from-popup-to-content-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!