TypeError: browser is undefined (Web Extension Messaging)

て烟熏妆下的殇ゞ 提交于 2019-12-24 17:16:09

问题


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:


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
});


来源:https://stackoverflow.com/questions/50378133/typeerror-browser-is-undefined-web-extension-messaging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!