3

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);
});
Community
  • 1
  • 1
wizloc
  • 2,202
  • 4
  • 28
  • 54
  • And what if you remove the alert? `onMessage` is not triggered if there is a blocking dialog in the content script: https://crbug.com/456482 – Rob W Feb 10 '16 at 17:27

1 Answers1

1

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 });
});
wizloc
  • 2,202
  • 4
  • 28
  • 54