I'm having trouble with receiving messages from both background.js and popup.js. I want to access the activeTab DOM content when clicking on button in popup. Here is the part manifest.json:
...
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"permissions": [
"tabs",
"activeTab",
"<all_urls>"
]
I send message from popup.js to background (and to content scrpit):
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("start_button").onclick = function() {
chrome.tabs.query({active:true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {
type: "start",
text: "task from popup to content"
});
});
});
But i can't recieve message from both background and popup in content.js:
function get_stuff_from_page(text) {
alert('recieved IN content:' + text);
var blocks_number = document.getElementsByTagName('div').length;
//how do i pass it back to background?
}
//i try to recieve it here and it doesn't work
chrome.extension.onMessage.addListener(function(message, sender, sendResponse) {
switch (message.type) {
case "start":
alert('recieved message 1');
get_stuff_from_page(message.text);
break;
}
});
//also doesn't work here
chrome.runtime.onMessage.addListener( function(message, sender, sendResponse) {
switch (message.type) {
case "start":
alert('recieved message 2');
get_stuff_from_page(message.text);
}
});
Where is my fault in receiving messages (or even in sending them)? I'm really confused because I tried most ways to do it and nothing works. And also how do I pass page's DOM back to background? Thanks in advance!
UPD: suggested answer (Popup script and content script can't communicate?) seems not to work for me. Maybe I'm missing something global?