Reputation: 265
in a popup.js of my extention, i want to create a new tab and send a message. content.js has to listen the message and answer but it doesn't work! i tried a lot of solution found in other question but without success here my files:
{
//Manifest.json
"name": "Stampa cedolini",
"description": "stampa automatica dei cedolini",
"version": "1.0",
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"content_scripts": [{
"matches": [ "http://*/*", "https://*/*"],
"js": [ "jquery-2.1.3.min.js" ,"content.js"]
}],
"browser_action": {
"default_title": "Scegli la persona.",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"manifest_version": 2
}
popup.js:
function click(e) {
var link1 = "http://www.example1.it";
var link2 = "http://www.example2.com";
if (e.target.id === "pippo") {
chrome.tabs.create({ url: link1 }, function(tab) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
// your code ...
chrome.tabs.executeScript({code:"console.log('"+tabs[0].id+"')"});
//chrome.tabs.executeScript({code:"alert("+tabs[0].id+");"});
chrome.tabs.sendMessage(tabs[0].id, {persona: "pippo"});
});
});
} else {
chrome.tabs.create({ url: link2 });
}
//window.close();
}
document.addEventListener('DOMContentLoaded', function () {
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', click);
}
});
and content.js:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
alert("from a content script:" + sender.tab.url);
if (request.persona == "pippo") {
sendResponse({risp: "ricevuto"});
}
});
the console.log(tab.id) in tabs.create callback is printed but seems that fails the send message Can someone help me?? thanks
Upvotes: 3
Views: 3783
Reputation: 77523
Your content script it loaded, by default, at document_idle
.
Which means that by the time you send the message, it's not there yet, and nothing listens to your message.
If you are creating a tab from code, it's best to programmatically inject your content script and not rely on the manifest injection, and use the callback to ensure it's done executing.
chrome.tabs.create({ url: link1 }, function(tab) {
// Why do you query, when tab is already given?
chrome.tabs.executeScript(tab.id, {file:"jquery-2.1.3.min.js"}, function() {
// This executes only after jQuery has been injected and executed
chrome.tabs.executeScript(tab.id, {file:"jcontent.js"}, function() {
// This executes only after your content script executes
chrome.tabs.sendMessage(tab.id, {persona: "pippo"});
});
});
});
That said, you may want to consider calling this code in the background script and not in the popup. As soon as popup loses focus, your popup page starts to unload and your code may not finish executing. It's better if you message the background script with a request to create the tab.
Upvotes: 13