JohnCalms
JohnCalms

Reputation: 87

TypeError: browser is undefined (Web Extension Messaging)

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?

Upvotes: 2

Views: 2974

Answers (1)

kartheek7895
kartheek7895

Reputation: 351

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 using browser.runtime.sendMessage. PFB sample code

window.onload = function(){
    document.dispatchEvent(new CustomEvent("myEvent",{
        detail:["Hello","World"]
    }));
}

contentscript.js

document.addEventListener("myEvent", function (event) {
browser.runtime.sendMessage({
    data: event.detail
});

background.js

browser.runtime.onMessage.addListener(function (message) {
     data = message.data;
     // do stuff
});

Upvotes: 3

Related Questions