This sample code demonstrates the connection between a Chrome extension and Firebase Realtime Database. Follow the steps below to set up and connect your extension.
- Go to Firebase Console.
- Create a new project or select an existing project.
- In the left sidebar, click on "Database" and choose "Create Database".
- Choose "Start in test mode" for security rules.
- Get the configuration keys for your Firebase project:
apiKey
authDomain
databaseURL
projectId
storageBucket
messagingSenderId
appId
-
Open
popup.js
in your Chrome extension project. -
Replace the placeholders with your Firebase configuration keys:
const config = { apiKey: "<YOUR_API_KEY>", authDomain: "<YOUR_AUTH_DOMAIN>", databaseURL: "<YOUR_DATABASE_URL>", projectId: "<YOUR_PROJECT_ID>", storageBucket: "<YOUR_STORAGE_BUCKET>", messagingSenderId: "<YOUR_MESSAGING_SENDER_ID>", appId: "<YOUR_APP_ID>" };
Locate window.onload and replace <YOUR_DB_REFERENCE> with the reference to your Realtime Database.
-
Load the Firebase script in your
popup.js
file:window.onload = function () { $.loadScript('https://www.gstatic.com/firebasejs/6.5.0/firebase.js', initializeFirebase); };
-
Add the following code to your
popup.js
file:function initializeFirebase() { firebase.initializeApp(config); // Replace `<YOUR_DB_REFERENCE>` with the reference to your Realtime Database const itemsRef = firebase.database().ref("<YOUR_DB_REFERENCE>"); // Listen for changes in the database itemsRef.on("value", snapshot => { const items = snapshot.val(); console.log(items); // Perform actions with the retrieved data }); }
Replace <YOUR_DB_REFERENCE> and other placeholders with your actual values.
- Open Chrome and go to
chrome://extensions/
. - Enable "Developer mode" in the top right corner.
- Click on "Load unpacked" and select the folder containing your extension files.
- Open your extension by clicking its icon in the Chrome toolbar.
- Open the Chrome DevTools (right-click on the extension icon -> "Inspect").
- Check the console for Firebase data retrieved from the Realtime Database.
Here you go! Your Chrome extension is now connected with Firebase Realtime Database.