I was working on a chrome browser extension. When I tried to connect firebase with the web app in 2 possible ways none is working.
import {initializeApp} from 'firebase/app';
import {getFirestore} from 'firebase/firestore';
The error which I got is
Uncaught TypeError: Failed to resolve module specifier "firebase/app". Relative references must start with either "/", "./", or "../".
import {initializeApp} from "https://www.gstatic.com/firebasejs/9.4.1/firebase-app.js";
import {getFirestore} from "https://www.gstatic.com/firebasejs/9.4.1/firebase-firestore.js";
As my project is a chrome extension, I have a manifest.json file which is in the following format:
{
"name": "xxx",
"manifest_version": 3,
"version": "1.0",
"permissions": ["cookies","tabs"],
"host_permissions": ["<all_urls>"],
"action": {
"default_popup": "popup.html"
},
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self'",
"sandbox": "sandbox allow-scripts; script-src 'self' 'https://apis.google.com/' 'https://www.gstatic.com/' 'https://*.firebaseio.com' 'https://www.googleapis.com' 'https://ajax.googleapis.com'; object-src 'self'"
}
}
The error which I was getting is:(something went wrong with the content_security_policy)
Refused to load the script 'https://www.gstatic.com/firebasejs/9.4.1/firebase-firestore.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
First, modify the imports as below:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.4.1/firebase-app.js";
import { getFirestore, collection, getDocs } from "https://www.gstatic.com/firebasejs/9.4.1/firebase-firestore.js";
You can find more information regarding it from the documentation. Since you are using a module bundler, needs type="module" to be added to it. The correct format should be:
<script type="module" src="........”></script>
Please note: src depends on how you set the path.
You may also refer to the video Getting started with Firebase for the web – Firebase Fundamentals. Also, the Cannot connect to Firebase,Uncaught Error in Firebase might add to it.
You should replace https://www.gstatic.com/ references in other files
in firebase-firestore.js
import { _registerComponent, registerVersion, _getProvider, getApp, _removeServiceInstance, SDK_VERSION } from 'https://www.gstatic.com/firebasejs/9.6.8/firebase-app.js';
change to line
import { _registerComponent, registerVersion, _getProvider, getApp, _removeServiceInstance, SDK_VERSION } from './firebase-app.js';