0

So, when i import some functions for firebase authentification, my login() function doesn't work.

This is my JS code:

import {signInWithEmailAndPassword} from "firebase/auth";
import { getAuth} from "firebase/auth";
const auth = getAuth();

const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};

var logindiv = document.getElementById("logindiv");
var signup = document.getElementById("signupdiv");
var userEmail = document.getElementById("email").value;
var userPass = document.getElementById("password").value;
function login(){

  logindiv.style.display = "block";
  signup.style.display = "none";
  signInWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {
    var user = userCredential.user;
    window.alert(userEmail+' '+userPass);
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
    window.alert(errorMessage);
  });
}

The first three lines(bolded) are my problems. This lines are there just so i can check my function since firebase isn't working.

logindiv.style.display = "block";
signup.style.display = "none";

This is my html code

<html>
    <head>
        <script src="https://www.gstatic.com/firebasejs/ui/6.0.1/firebase-ui-auth.js"></script>
        <link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/6.0.1/firebase-ui-auth.css" />
    </head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <body>
        <div class="login_form">
            <div>
                <h1 id="title">Welcome Back</h1>
            </div>
            <div id = 'logindiv' class = 'login_info'>
                <input type="input" class="form_field" placeholder="Email" name='name' size = 50 id="email" required/>
                <input type="input" class="form_field" placeholder="Password" name='password' size = 50 id="password" required/>
                <a id = 'forgot'>Forgot password ?</a>
                <button onclick="login()" class="loginbutton" font-color = black>Log in</button>
            </div>
            <div class="loginSignupSeparator"></div>
            <div id="signupdiv">
                <form action="signup.html">
                    <button class="signupbutton" onClick="login()" wype = 'submit' name='button' font-color = black required>Sign up</button>
                </form>
            </div>
                
        </div>
    </body>

    
    <style>
    .loginSignUpSeparator {
        border-top: 1px solid #cbd2d6;
        position: relative;
        margin-top: 6%;
        margin-bottom: 3%;
        height: 15px;
        text-align: center;
        font-size: 83.34%;
        margin-left: 10%;
        margin-right: 10%;
    }   
        #forgot{
            font-family: Helvetica;
            color: #3333ff;
            font-size: 15px;
            display: block;
            margin-top: 8px;
            margin-left: 5%;
            font-weight: bold;
        }

        @font-face {
            font-family: 'D:/peace 2/resources/PlayfairDisplay-Regular';
            src: url(PlayfairDisplay-Regular.otf);
        }
        @font-face {
            font-family: 'D:/peace 2/resources/Helvetica';
            src: url(Helvetica-Bold.ttf);
        }
        @font-face {
            font-family: 'D:/peace 2/resources/HelveticaRegular';
            src: url(Helvetica.ttf);
        }
        body{
            background-color: white;
        }
        #title{
            display: block;
            font-size: 50px;
            padding-top: 5%;
            text-align: center;
            font-family: "PlayfairDisplay-Regular";
        }
        .login_form{
            border-radius: 15px;
            border: 2px solid #eaeced;
            background-color: white;
            display: block;
            margin-left: auto;
            margin-right: auto;
            margin-top: 70px;
            width: 30%;
            height: 80%;
        }

        .login_info{
            font-family: inherit;
        }
        @media screen and (max-width: 800px){
                .login_form{
                    width: 80%;
                    display: block;
                    margin-left: auto;
                    margin-right: auto;
                    margin-top: 10px;
                    border: 0px solid #eaeced;
                }
            }
        .form_field{
            transition: border .2s ease-in-out,background-color .2s ease-in-out;
            display: block;
            margin-top: 30px;
            margin-right: auto;
            margin-left: auto;
            height: 12%;
            border-radius: 3px;
            border: 1px solid gray;
        }
        
        .loginbutton{
            font-family: Helvetica;
            font-size: 15px;
            border: 0px;
            border-radius: 25px;
            background-color:  #3333ff;
            display: block;
            margin-right: auto;
            margin-left: auto;
            margin-top: 3%;
            height: 8%;
            width: 81%;
            color: white;
        }
        .signupbutton{
            font-family: HelveticaRegular;
            font-size: 15px;
            border: 1px solid blue;
            border-radius: 25px;
            background-color:  white;
            display: block;
            margin-right: auto;
            margin-left: auto;
            margin-top: 3%;
            height: 8%;
            width: 81%;
            color: blue;
        }

    </style>


    <script src="./script.js"></script>

</html>

I tried everything i know, still nothing. I am new to firebase and js also. I cannot understand why my functions just isn't working when i import that firebase functions.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Can you explain "doesn't work"? Do you get any errors in the console? – Dharmaraj Oct 27 '22 at 08:51
  • @Dharmaraj i don't have any error. Just, the function doesn't work. it Does nothing – David Bell Oct 27 '22 at 09:06
  • Uncaught ReferenceError ReferenceError: login is not defined at onclick (d:\peace 3\lib\index.html:16:82) I get this when i have the first 3 lines of js code – David Bell Oct 27 '22 at 09:06
  • Uncaught ReferenceError ReferenceError: signInWithEmailAndPassword is not defined at login (d:\peace 3\lib\script.js:32:3) at onclick (d:\peace 3\lib\index.html:16:82 This is what i get when i don't have the first 3 lines of js code – David Bell Oct 27 '22 at 09:07
  • The error clearly tells `login` and `signInWithEmailAndPassword()` functions are not defined. Maybe you did not import them properly? Can you share the complete code instead of small snippets? – Dharmaraj Oct 27 '22 at 09:10
  • I actually shared the full code. There are two cases: My login function works(is defined) when i remove signInWithEmailAndPassword() import from code. Second case is when my login function is not defined when the import for signInWithEmailAndPassword() is in the code. – David Bell Oct 27 '22 at 09:13
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Oct 27 '22 at 10:20

1 Answers1

2

Your problem seems to be due to the use, directly in HTML, of a function defined in a ES6 module.

See also "access to script from origin 'null' has been blocked by CORS policy" error while trying to launch an html page using an imported js function: "You cannot use a script file as a module without using a server."

The following should do the trick:

.js file

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.9.4/firebase-app.js';

// Add Firebase products that you want to use

import { getAuth, signInWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.9.4/firebase-auth.js';

const firebaseConfig = {
  // ...
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

const logindiv = document.getElementById("logindiv");
const signup = document.getElementById("signupdiv");
const userEmail = document.getElementById("email").value;
const userPass = document.getElementById("password").value;

function login() {
      signInWithEmailAndPassword(auth, userEmail, userPass)
        .then((userCredential) => {
            var user = userCredential.user;
            window.alert(userEmail + ' ' + userPass);
        })
        .catch((error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            window.alert(errorMessage);
        });
}

document.querySelector('button').addEventListener('click', login); // Adapt the selector mode as desired

html file

<!DOCTYPE html>
<html>
  <body>
    <button ">Log in</button>
    <script type="module" src="./script.js"></script>
  </body>
</html>

Note also that with your current code

var logindiv = document.getElementById("logindiv");
var signup = document.getElementById("signupdiv");
var userEmail = document.getElementById("email").value;
var userPass = document.getElementById("password").value;
function login(){

  logindiv.style.display = "block";
  signup.style.display = "none";
  signInWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {
    var user = userCredential.user;
    window.alert(userEmail+' '+userPass);
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
    window.alert(errorMessage);
  });
}

email and password are undefined. This errors should normally be catched in your catch block and an alert displayed in your browser (window.alert(errorMessage);).

Doing

  signInWithEmailAndPassword(auth, userEmail, userPass)
  .then((userCredential) => {
    var user = userCredential.user;
    window.alert(userEmail+' '+userPass);
  })

should solve the problem.


Note that, as explained in the doc, you should probably use a module bundler or a JavaScript framework to work with the modular V9 SDK.

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • Thanks. i didn't see that. however, something still doesn't work. This is when i have the first 3 lines of js code: Uncaught ReferenceError ReferenceError: login is not defined at onclick (d:\peace 3\lib\index.html:16:82) This is when i don't have the first 3 lines of js code: Uncaught ReferenceError ReferenceError: signInWithEmailAndPassword is not defined at login (d:\peace 3\lib\script.js:32:3) at onclick (d:\peace 3\lib\index.html:16:82) VS Debug Console – David Bell Oct 27 '22 at 09:03
  • How do you import your JS file in your HTML file? – Renaud Tarnec Oct 27 '22 at 09:08