I have this issue. I saw this question and tried its solution but it does not seem to work. The error disappears but the code does not do what it's supposed to do.
So, basically, I have a background script that uses XMLHTTPSrequest to inject a content script in all the pages that are http or https.
background.js:
chrome.browserAction.onClicked.addListener(function (event) {
show_floater = !show_floater;
// inject content script in tabs
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://127.0.0.1/js/test1.js", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
chrome.tabs.query({ currentWindow: true }, (tabs) => {
tabs.forEach(function(e) {
if (/http:/.test(e.url) || /https:/.test(e.url)) {
chrome.tabs.executeScript(e.tabId, { code: xhr.responseText }, () => {
connect(show_floater);
console.log(e.url);
});
}
else
console.log('e: ' + e.url);
});
});
}
}
xhr.send();
});
The content script then does it's magic on the page and sends a message back to the bg when a user action occurs.
content.js
chrome.runtime.sendMessage({}, function (response) {
console.log('sent');
let msgData = { text: "am I connected?" };
chrome.runtime.sendMessage(JSON.stringify(msgData));
});
and here is how bg handles the messages:
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
console.log('I AM HERE');
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (/http:/.test(e.url) || /https:/.test(e.url)) {
const port = chrome.tabs.connect(tabs[0].id);
msg = JSON.parse(msg);
if (msg.text == "am I connected?") {
//do stuff
}
}
});
// return true;
});
the answer I was looking at said to add a 'return true' at the end. I tried and the error goes away but the console.log does not appear... HALP!