Reputation: 4855
What's the best way to test the code of an event listener in background.js in a Chrome extension with no UI?
Let's say I have the following background.js:
chrome.runtime.onMessage.addListener(request => {
console.log(request);
});
I now want to debug different kinds of messages (e.g. chrome.runtime.sendMessage('someMessage')
) and see the console.log
be executed. I've tried using Chrome's DevTools for the background page and trying to sendMessage
form the console but the console.log
line is not getting hit.
Any help would be appreciated.
Upvotes: 3
Views: 1519
Reputation: 77502
(emphasis mine)
I've tried using Chrome's DevTools for the background page and trying to
sendMessage
form the console but theconsole.log
line is not getting hit.
A message sent in an extension page using chrome.runtime.sendMessage
is not fired as an event in the same page. This is to prevent outgoing messages to be needlessly handled by the sender.
You'll need to create another page and testing from there.
It can be as minimal as a blank HTML file "test.html" you just open with chrome-extension://<your-extension-id>/test.html
in a tab and then use the console from there.
Or, you can test from a content script (it's allowed to use chrome.runtime.sendMessage
), but be mindful of the context selected at the top of the console (normally reads "top" for the page's main frame).
Upvotes: 1