Lotherad
Lotherad

Reputation: 125

Content script is not getting message

My background script is opening a new tab, and then executing jQuery on this tab, then I execute my script and send my message that this script needs.

The thing is that script is not receiving the message.

background.js

chrome.tabs.create({url: myUrl}, function(tab){
        chrome.tabs.executeScript(tab.id, {file: 'jquery-2.1.4.min.js'}, function(){
            chrome.tabs.executeScript(tab.id, {file: 'myScript.js'});
            chrome.tabs.sendMessage(tab.id, {myMessage: message.myMessage});
            })
        });

myScript.js

alert('It works!');

chrome.runtime.onMessage.addListener(function(message) {
    alert('Also here!');
});

So "It works!" pops out but "Also here!" does not.

Upvotes: 1

Views: 577

Answers (1)

jnfsaopfnsaopfnb
jnfsaopfnsaopfnb

Reputation: 36

As chrome.tabs.executeScript is async, you also have to wait for myScript.js to be loaded before you send messages to it:

chrome.tabs.create({url: myUrl}, function(tab){
    chrome.tabs.executeScript(tab.id, {file: 'jquery-2.1.4.min.js'}, function(){
        chrome.tabs.executeScript(tab.id, {file: 'myScript.js'}, function(){
            chrome.tabs.sendMessage(tab.id, {myMessage: message.myMessage});
        });
    });
});

Upvotes: 2

Related Questions