I am trying to communicate my web page script with my content script of my web extension with the code below
Web Page Script
const browser = window.browser || window.chrome;
browser.runtime.sendMessage(message,
function (response) {
console.log(response);
}
);
However, I keep getting the error TypeError: browser is undefined
. The same goes if I use chrome.runtime.sendMessage()
instead.
How am I supposed to use this method?
The issue here is that user/webpage scripts (unprivileged scripts) don't have access to JavaScript API for security purposes and
browser
,chrome
are part of JavaScript APIs which can only be accessed by privileged scripts like web extension's background scripts and content scripts (again content scripts don't have access to all the JavaScript APIs). Basically, if you need to send data from web page script to background script,CustomEvent
should be used to send data to a content script which acts as a bridge and from there send that data to background script usingbrowser.runtime.sendMessage
. PFB sample codecontentscript.js
background.js