Reputation: 451
I want to create a chrome extension, that can to this:
In my popup.html i do this:
$("#openLink").click(function () {
chrome.runtime.sendMessage({greeting: "GetURL"},
function (response) {
});
});
After this i click this button, i catch this message and create a new tab here: (background.js)
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.greeting === "GetURL") {
var tabURL = "Not set yet";
chrome.tabs.create({
url: "http://google.de"
}, function (tab) {
//chrome.tabs.sendMessage(tab.id, {greeting: "hello"});
chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function (response) {
});
});
}
});
As you can see, i get the tab id and a try to send message to this tab. But how can i get that message in my content script? I use this, but it doesn't work:
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
alert('s');
console.log('s');
});
Upvotes: 0
Views: 3079
Reputation: 5118
My proposed solution would be modifying your background script to inject the content script programmatically, like:
background.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.greeting === "GetURL") {
var tabURL = "Not set yet";
chrome.tabs.create({url: 'http://google.de'}, function (tab) { //create tab
chrome.tabs.executeScript(tab.id, {file: 'content.js'}, function(){ //inject content script
chrome.tabs.sendMessage(tab.id, {greeting: "hello"}); //send message to content script
});
});
}
});
Upvotes: 1