When I try to reload the page, JavaScript ceases to function

Check out this JavaScript code snippet:

var input = document.getElementById("password_field");
input.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
   event.preventDefault();
   document.getElementById("login").click();
  }
});

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        document.getElementById("user_div").style.display = "block";
        document.getElementById("login_div").style.display = "none";

        var currentUser = firebase.auth().currentUser;

        if(currentUser != null) {
            var emailId = currentUser.email;
            var isEmailVerified = currentUser.emailVerified;
            document.getElementById('user_para').innerHTML = "You are logged in as<strong> " + emailId + "</strong>.";
            if (isEmailVerified === false) {
                document.getElementById('user_verified').innerHTML = "<strong>You are not verified. Please check for an email from perason for a verification link. You will not be able to access anything without verification.";
            } else {
                document.getElementById('user_verified').innerHTML = "";
                document.getElementById('sandboxaccess').style.display = "block";
            }
        }
      
    } else {
        document.getElementById("user_div").style.display = "none";
        document.getElementById("login_div").style.display = "block";
    }
});

function loginUser() {
    var userEmail = document.getElementById('email_field').value;
    var userPass = document.getElementById('password_field').value;

    firebase.auth().signInWithEmailAndPassword(userEmail, userPass).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        window.alert("Error: " + errorMessage);
      });
}

function logoutUser() {
    firebase.auth().signOut();
}

The script functions correctly at first, but upon page refresh, the JavaScript functionality ceases. Interestingly, it works fine on Apache localhost even after refreshing. How can this issue be resolved?

Snapshot before refresh:

before refresh

Snapshot after refresh:

after refresh

Note that the logout button appears in both snapshots.

Review errors on console

Answer №1

Make sure to eliminate this code line from your script:

const currentUser = firebase.auth().currentUser

Remember that you already have a currentUser object within the parameter of your callback function. Using the currentUser returned here might replace the correct one currently being utilized.

Answer №2

It seems like the code is running before the DOM has fully loaded.
What do you think of trying this approach instead:

document.addEventListener('DOMContentLoaded', function (){
  // Add your code here
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing AngularJS to show content based on regular expressions using ng-show

With two images available, I need to display one image at a time based on an input regex pattern. Here is the code snippet: <input type="password" ng-model="password" placeholder="Enter Password"/> <img src="../close.png" ng-show="password != [ ...

The error message "Uncaught ReferenceError: require is not defined" is commonly encountered when using Webpack

Despite countless similar questions, none have provided a solution to my issue because the underlying problem seems to elude me. I am attempting to bundle files for the browser using webpack 4.26.1, but no matter what I try, I consistently encounter the er ...

"Creating a dynamic TreeList in Ignite UI by linking pairs of names and corresponding

I recently developed a drag and drop tree list inspired by the tutorial on IgniteUI website. The main tree list functions properly, but I encountered an issue with the child nodes displaying as undefined, as illustrated in the image below: https://i.sstat ...

Is there a way to continuously send out this ajax request?

My attempt to use setInterval for sending an AJAX request every 2 seconds is causing the page to crash. It seems like there is something wrong in my code! Check out the code below: var fburl = "http://graph.facebook.com/http://xzenweb.co.uk?callback=?" ...

Declaration file for chessboardjs TypeScript (automatic import)

With the goal of creating high-quality declaration files for DefinitelyTyped, I am now tackling the https://github.com/oakmac/chessboardjs/ library. I have successfully imported it as follows: // CURRENT IMPORT import * as ChessBoard from "chessboardjs"; ...

Adding schemas to the router of a Next.js 13 app is a helpful feature that can

Summary: In Next.js 13, the /app router's new changes to layout and page routing have altered how we add content to the <head>. The challenge now is how to include a schema script on each page. Next.js automatically combines <head> tags f ...

Retrieve the selected value from a radio button

I am attempting to display the chosen value in an input field when a radio button is selected. However, the functionality seems to be broken when I include bootstrap.min.js. You can find the code on JSFiddle. $('input:radio').click(function() ...

Need to save a file to a specific directory using AngularJS or JavaScript? Here's how!

I'm currently developing in AngularJS and using fileSaver.js to export files, which are saved in the download folder. However, I am seeking a way to export or download selected files directly to the desktop location. Is there another solution availabl ...

What is the best way to determine the actual height of a DOM element that is being hidden by the overflow property in order to create a seamless CSS transition to height: auto

Solution: Thanks to @Kalimah, here's a solution that works in composition api & script setup: <script setup> const state = reactive({ meetCardHeight: 100 }) const element = ref(null) const changeElementHeight = () => { if (stat ...

Guidelines for showing an image using a Jquery tooltip

In my HTML document, I have a container with an image file name: <div class="productPic blockField"> myphoto.jpg </div> To display the image, I assigned it to a variable: var imageUrl = '<img src="images/myphoto.jpg" />'; ...

Refreshing the DeckGL HexagonLayer upon changes to the data array/Initiating a reload for the DeckGL HexagonLayer

I am currently using DeckGL along with React to showcase data on an OpenStreetMap. My goal is to incorporate filters to allow for different views of the data I possess. The main issue I encounter is the inability to refresh the layer representing the data ...

Setting up a functionality for a PHP-generated select option

When the main select tag "category" is changed, it triggers a PHP script to display a new select tag: <select id="category" onchange="showme(this);"> <option value="txt">text</option> <option value="img">image</ ...

Empty screen appears when "npm run serve" command is executed following the build process

I am currently utilizing Material-ui. Following the project build with npm run build, I encounter a blank page when running npm run serve. I attempted to set homepage: "./" in the package.json as suggested here, however, it still displays a blank ...

When loading a page with Puppeteer using the setContent method, images may not be loaded

Currently, I am experiencing an issue with Puppeteer where it does not load resources that are specified with relative paths (such as background.png in the image src or in CSS url()). When I try to load the content of a local file using setContent(), the o ...

Is it possible to display the command output in Grunt as it runs?

When I run this command, I am not seeing any output and it runs endlessly: grunt.registerTask('serve', function () { var done = this.async(); grunt.util.spawn({ cmd: 'jekyll', args: ['serve'], ...

The Jquery code is failing to execute the AJAX GET request

I've included jQuery in my code, but despite that, it seems like my script is not functioning properly. I suspect the issue lies with how I am loading jQuery rather than with my ajax request. There are no error messages appearing and the console.log ...

Customize the background color of InfoBox in Google Maps API V3 using a dropdown menu

I'm attempting to dynamically change the background color of an InfoBox by using a Dropdown list (this InfoBox is used to create map labels). I am using google.maps.event.addDomListener, but the values are not returning. Below is my code, can anyone i ...

Using Lambda functions as a module in node.js

I have come up with an idea to run the lambda function below as a node module. Node.js Server: var express = require('express'); var app = express(); var server = require('http').Server(app); server.listen(2006, function () { co ...

interactive vuetify navigation trail elements

Currently working on a vuetify project and I'm facing an issue with implementing breadcrumbs. The problem arises when clicking on a breadcrumb, as it deletes the ones that come after it in the list. I've tried some code snippets but could only ma ...

Creating a flash message following a redirect in AngularJS

Just diving into Angular JS and need some clarification. How can I set a flash message after a redirect? Here's my scenario: I have a form where I save data using an HTTP request. Upon success, I navigate to another page using window.location(). Now, ...