Chrome tab.create and tab.getSelected

后端 未结 1 647
一生所求
一生所求 2021-02-11 07:41

I have some problems to pass message from background page to my content_script.js. I hope someone can point out where i am wrong.

background.html

//in          


        
相关标签:
1条回答
  • 2021-02-11 08:03

    The background.html can be simplified to:

    //in a function
    function myFunction() {
        chrome.tabs.create({"url":"myurl","selected":true}, function(tab){
            makeRequest(tab.id);
        });
    }
    
    //make request
    function makeRequest(tabId) {
        chrome.tabs.sendRequest(tabId, {greeting: "hello"}, function(response) {
            console.log(response.farewell); 
        });
    }
    

    If it still doesn't work correctly then it might be because the tab hasn't finished loading (log tab.status in the chrome.tabs.create callback to check if this is true). There are two solutions for this, or you add an listener to chrome.tabs.onUpdated while filtering for this tab id or you make the tab send the request instead of background.html.

    0 讨论(0)
提交回复
热议问题