I've asked for help to understand how to implement correctly the message API for chrome extension, then I've implemented it in my code.
The workflow is that the popup.js will send a message to my background script to let it know that the popup is opened and available to receive data, then the background script is sending a message to the content script that will grab the desired data and send back a response with these data. I get an error in the popup.js console: Uncaught TypeError: chrome.runtime.onMessage is not a function
. I've also noticed that the content script is not fired on message, Is there any fix for this, what's wrong with the code?
popup.js
(function($){
$(document).ready(function(){
console.log('Extension Started!');
chrome.runtime.sendMessage({type:'init_popup_feed'});
chrome.runtime.onMessage(function(message, sender, response){
console.log(sender);
if( message.type == 'feed_data' ){
console.log(message.data);
}
});
});
}(jQuery));
background.js
const s = [];
chrome.runtime.onMessage.addListener(function(message, sender, response){
console.log(sender);
console.log(message.type);
if( message.type == 'init_popup_feed' ){
chrome.runtime.sendMessage({type:'grab_feed'});
}
else if( message.type == 's_feed'){
chrome.runtime.sendMessage({type:'feed_data',data:message.data});
}
//chrome.runtime.sendMessage({});
});
main.js - content script
(function($){
$(document).ready(function(){
console.log('Extension Started!');
const l = [];
var d;
chrome.runtime.onMessage.addListener(function(message, sender, response){
console.log(message.type);
if( message.type == 'grab_feed' ){
// ... code stuff here ...
sendResponse({type:'s_feed',data:l});
console.log(l);
}
});
});
}(jQuery));
UPDATE
I've modified the code according to the suggestion in the comments. Now I have an error in the background script console log : Error in event handler: TypeError: Error in invocation of tabs.sendMessage(integer tabId, any message, optional object options, optional function responseCallback): No matching signature.
what's wrong with the chrome.tabs.sendMessage()
?
background.js
var id;
chrome.runtime.onMessage.addListener(function(message, sender, response){
console.log(message.type);
if( message.type == 'extension_started'){
console.log(sender);
id = sender.tab.tabId;
}
else if( message.type == 'init_popup_feed' ){
chrome.tabs.sendMessage(id, {type:'grab_stories'}, function(response){
console.log(response);
chrome.runtime.sendMessage({type:'stories_feed_data',data:response.data});
});
}
});