I'm building a Chrome extension and want to access a background script global variable from the content script, so I'm using the browser runtime API to pass messages between the content and background scripts.
This results in "Uncaught ReferenceError: browser is not defined" Image of error message
content script:
//alert for debugging purposes
alert("content.js is loaded.");
document.body.onLoad = sending;
function sending(){
//alert for debugging purposes
alert("content.js is loaded, and sending() has been called.");
//sends a Promise to the receiver
document.addEventListener('DOMContentLoaded', function() {
browser.runtime.sendMessage({
type: "getText"
}).then(function(message) {
alert("Value of text is: ", message.result);
});
}
background script:
//alert for debugging purposes
alert("background.js is loaded.");
//'text' is the variable I'm trying to access from content script.
var text = prompt("Why are you here on this page?","E.g: To watch Daniel Schiffman's first video.");
//add a listener for the message sent from the content script
browser.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type == "getText") {
//alert for debugging purposes
alert("browser.runtime is working from background.js");
//send the response to content script
sendResponse({result: text});
}
});
Notes
browser.* with chrome.*. The error message disappears, but the alerts inside the browser.runtime functions don't appear when I refresh the page, meaning the sendMessage() and onMessage() did not execute.var browser = browser || chrome;, which is essentially the same thing as above.You need the types for the chrome global object.
You can obtain them auto-magically by installing the package @types/chrome.
I personally prefer yarn but npm will do it as well.
yarn add @types/chrome
Use chrome not browser, whether in Firefox or Chrome, the APIs are the same as far as I've explored them.
The API documented by google will work on firefox and chrome - to my limited knowledge - but if you refer to the MDN documentation it will be the same except that you use chrome instead of browser as the object to operate on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With