TypeError: browser is undefined (Web Extension Mes

2019-08-09 02:22发布

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?

1条回答
在下西门庆
2楼-- · 2019-08-09 03:06

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
});
查看更多
登录 后发表回答