quirky purple
quirky purple

Reputation: 2219

onMessage not being executed on Chrome extension

Referencing this post, I am trying to use executeScript or sendMessage to pass a variable to my content.js file. Using Chrome dev tools, I see that it is reaching my content.js file, and it also runs the test alert I insert, but when it gets to the

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {

it skips it entirely. I'm not sure what is happening here?

popup.js

function search() {
    var name = document.getElementById('txtSearch').value;
    chrome.tabs.executeScript({ file: "jquery.js" }, function () {
        chrome.tabs.executeScript(null, {
            code: 'var name = ' + name + ';'
        }, function () {
            chrome.tabs.executeScript({ file: 'content.js' });
        });
    });
}
document.getElementById('btnSearch').addEventListener('click', search);

or popup.js using sendMessage

function search() {
    var name = document.getElementById('txtSearch').value;
    chrome.tabs.executeScript({ file: "jquery.js" }, function () {
        chrome.tabs.executeScript({ file: 'content.js' }, function () {
            chrome.tabs.sendMessage({ name: name });
        });
    });
}
document.getElementById('btnSearch').addEventListener('click', search);

content.js

alert('hi');
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    console.log(message.name);
});

Upvotes: 3

Views: 134

Answers (1)

quirky purple
quirky purple

Reputation: 2219

Referencing a different answer I found on SO (cant find it atm), I was missing a function to pass the tab id to the content script.

chrome.tabs.query({ active: true }, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {'type': type, 'name': name });
});

Upvotes: 1

Related Questions