"how to use firebase database in chrome extension" Code Answer


contentscript runs on page's dom, but on different js sandbox, so you can't directly inject js via dom as it is shown in the example.

i would recommend you to load firebase lib to the background page and then you can access it from your background script and proxy requests from your content script via background backend. this will not cause firebase lib loaded every time you load page loads content scripts and it will be load once on background page init (or you can load it by request using non-persistent background script).



    "manifest_version": 2,
    "name": "firebase demo",
    "description": "firebase client demo",    
    "version": "0.0.1",
    "permissions": [
     "background": {
       "page": "bg.html",
       "persistent": false
     "content_scripts": [{
        "matches": ["https://*/*","http://*/*"],
        "js": ["cs.js"]
     "content_security_policy": "script-src 'self' https://www.gstatic.com/firebasejs/5.3.0/firebase.js; object-src 'self'"


        <script src="https://www.gstatic.com/firebasejs/5.3.0/firebase.js"></script>
        <script src="bg.js"></script>


  apikey: '...',
  authdomain: '...',
  projectid: '...'

var db = firebase.firestore();
db.settings({timestampsinsnapshots: true});
  chrome.runtime.onmessage.addlistener((msg, sender, response) => {
    if (msg.command == "add"){
      console.log("process msg add", msg, sender, response);
      db.collection(msg.collection).add(msg.data).then((result) => {
        console.log("success", result)
        response({type: "result", status: "success", data: result, request: msg});
      }).catch((result) => {
        console.log("error", result);
        response({type: "result", status: "error", data: result, request: msg}); 
    return true;


chrome.runtime.sendmessage({command: "add", collection: "users", data: {name: "user"}}, (msg) => {
  console.log("response", msg)

another variant is to load your firebase js lib and the code you need to run to the page's js sandbox by injecting it to the page's dom with something like:

var script = document.createelement("script");
script.src = "https://www.gstatic.com/firebasejs/5.3.0/firebase.js"
document.body.append(script); // firebase lib will be loaded to the page's js sandbox and page's dom
var fn = function injectedfunction(seed) { /* your js code you want to run is page's sandbox */ }
var ele = document.createelement("script");
ele.textcontent = fn+"console.log(injectedfunction());";

but this variant is very bad, because page's csp may block your js in this case. document.body.appendchild(ele);

By David Henty on September 19 2022

Answers related to “how to use firebase database in chrome extension”

Only authorized users can answer the Search term. Please sign in first, or register a free account.