Home > Mobile >  Uncaught Reference Error : firebase not defined at main.js
Uncaught Reference Error : firebase not defined at main.js

Time:10-22

Am trying to Connect Firebase to a Contact Form, where requires the user to type and submit Fullname , Email and also Message. But I face Uncaught ReferenceError: firebase is not defined at my main.js file form my console. I tried different solution but I couldn't be able to solve it.

Here is my script tag in my index.html


<script type="module">
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
  </script>
  
<script src="main.js"></script>

here is my Main.js code

var config = {
  apiKey: "xxxxx",
  authDomain: "xxxxx",
  databaseURL: "xxxxx",
  projectId: "xxxxx",
  storageBucket: "xxxxx",
  messagingSenderId: "xxxxx"
};

firebase.initializeApp(config);


var emailRef = firebase.database().ref('emails');


  // Listen for form submit
  document.getElementById('contactForm').addEventListener('submit', submitForm);

// Submit form
function submitForm(e){
  e.preventDefault();

    //Get values
    var FullName = getInputval('FullName');
    var Email =getInputval('Email');

        // save message
        saveMessage(FullName,Email);
  
    // Show alert
    document.querySelector('.alert').style.display = 'block';
  
    // Hide alert after 3 seconds
    setTimeout(function(){
      document.querySelector('.alert').style.display = 'none';
    },3000);
  
    // Clear form
    document.getElementById('contactForm').reset();
  }
  

// Function to get  form values
function getInputval(id){
    return document.getElementById(id).value;
}

  
  // Save message to firebase
  function saveMessage(Fullname, Email,){
    var newEmailRef = emailRef.push();
    newEmailRef.set({
      Fullname: Fullname,
      Email:Email

    });
  }


CodePudding user response:

Since you're initializing firebase here, it should be something like this:

const firebase = initializeApp(config);

For more info you can have a look here.

CodePudding user response:

First, you need to install the firebase/app with this command:

npm install firebase

then, in your Main.js:

const firebase = require("firebase/app") 

Now you can initialize it properly:

const firebase = require("firebase/app") 

var config = {
  apiKey: "xxxxx",
  authDomain: "xxxxx",
  databaseURL: "xxxxx",
  projectId: "xxxxx",
  storageBucket: "xxxxx",
  messagingSenderId: "xxxxx"
};

firebase.initializeApp(config);
  • Related