I am getting started playing with Chrome extensions and passing messages between the content script and the background script. I've followed some tutorials and it is going pretty well, but there is an issue I am having with passing a message with a URL and not being able to always interact with it. The simplest example I can come up with is just logging the URL. I can use the URL and my new tab opens meaning my code is working for its intention. Heck, I even tried just logging some text and it will not go to the console.
// background.js
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function (tab) {
// Send a message to the active tab
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, { "message": "clicked_browser_action" });
});
});
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.message === "open_new_tab") {
console.log("Does this get logged?"); // This is not getting logged
console.log("passedUrl: " + request.url); // This is not getting logged
chrome.tabs.create({ "url": request.url }); // This works fine
}
}
);
// JavaScript source code
// content.js
console.log("hello"); // This gets logged
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.message === "clicked_browser_action") {
var firstHref = $("a[href^='http']").eq(0).attr("href");
console.log(firstHref); // This gets logged
chrome.runtime.sendMessage({ "message": "open_new_tab", "url": firstHref });
}
}
);