0

In my admin.html I called checkIfUserLogedIn() function when the page is loading

<!DOCTYPE html>
<html>
    <head>
        <title>Admin</title>
    </head>
    <body onload="checkIfUserLogedIn()">
        <h1>Admin Pannel</h1>
        <script src="./main.js"></script>
    </body>
</html>

In main.js I imported my checkIfUserLogedIn() function from checkUser.js file.

import firebase from 'firebase/app';
import "firebase/auth";
import checkIfUserLogedIn from './checkUser';

checkUser.js file looks like this

import firebase from 'firebase/app';

export default function checkIfUserLogedIn() {
    const user = firebase.auth().currentUser;

    if (user) {
        console.log(user)
    } else {
        console.log("user loged out")
    }
}

This is the index.html file entry point of the project

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sign In</title>
    <link rel="stylesheet" href="./style.css">
</head>
<body>
    
    <div class="form-container">
        <h1>Sign In</h1>
        <form method="post" id="signin-form">
            <input type="email" name="email" id="signin-email" placeholder="Email" required="true"> <br>
            <input type="password" name="password" id="signin-password" placeholder="Password" required="true"> <br>
            <input type="submit" value="Sing In" class="btn">
        </form>
        
        <p><a href="./signup.html">Create New Account</a></p>
        <p><a href="./admin.html">Create New Account</a></p>
    </div>
    

    <script src="./main.js"></script>
</body>
</html>

I want to call checkIfUserLogedIn() function when the admin.html file is loading but I give an Uncaught ReferenceError: checkIfUserLogedIn is not defined error.

Murat Colyaran
  • 2,075
  • 2
  • 8
  • 27
Eranda
  • 1
  • 1
  • 1
  • Remove the attribute and in your main script, add `window.addEventListener("load", checkIfUserLogedIn);` –  May 31 '21 at 11:32
  • I want to run that function only when admin.html file loading – Eranda May 31 '21 at 11:45
  • Right, then do `` in admin.html and check `document.body.classList.contains("admin")` first –  May 31 '21 at 11:54

1 Answers1

0

I solve the problem. Thanks to chris-g

I added "admin" class to the admin.html page body. Then in my main.js file, I checked if the body has a class called "admin" if it has then added a load event listener.

if(document.body.classList.contains('admin')) {
        window.addEventListener('load', checkIfUserLogedIn)
}
Eranda
  • 1
  • 1
  • 1