Using `location.reload()` and `location.replace(url)` does not seem to function properly when using Electron with Angular

Using Electron to rebuild a pre-existing web app, the main.js file in electron is kept simple:

// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow () {
  // Create the browser window.
   mainWindow = new BrowserWindow({
        width: 1600, 
        height: 900
  })

  // and load the index.html of the app.
  mainWindow.loadFile('dist/mysite/index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

When running the app using 'electron .', everything works fine except for the line concerning location. The issue lies within the login submit form action. After logging in, the line 'location.reload()' does not work as intended:

this.http.post(this.url + ':8000/' + 'auth/jwt/create/', this.validateForm.value)
  .subscribe((res: any) => {
    localStorage.setItem('token', res.token);

// This LINE NOT WORK 
location.reload();
// //////

    // this.router.navigate([this.router.url]);
    // this.router.navigate(['./']);
    console.log(location);
  }, (err: any) => {
    if (err.status === 400) {
      this.msg = err.error.non_field_errors[0];
      console.log(err);
    } else {
      this.msg = err;
      console.log(err);
    }
    this.isVisible = true;
  });

Attempts have been made to get the web page to navigate to the target URL, but methods such as location.reload(), location.replace, and router.navigate have all failed. Interestingly, when using 'ng serve' and opening the site in Chrome, 'location.reload()' works without any issues. What could be causing this inconsistency? Any guidance or suggestions would be greatly appreciated.

EDIT: Upon execution of location.reload(), the page goes blank. Additionally, when console.log(location) is performed, the href reads chrome-error://chromewebdata/

console.log(location)  
Location {replace: ƒ, assign: ƒ, href: "chrome-error://chromewebdata/", ancestorOrigins: DOMStringList, origin: "null", …}

Answer №1

After adding a Listener to my

browserView.webContents.on('will-navigate', ...);
, the functionality stopped working for me. I noticed that by stopping some events, it was causing page reloading to be blocked.

Answer №2

When working with Angular, it is recommended to utilize window.location.reload() as the window object is a shared object that can be accessed from anywhere, including localStorage.

window.location.reload()

You can also use console.log(location) and console.log(window.location) to see the distinction between them.

Answer №3

It's important to note that the issue at hand is not related to how the window.location.reload() function is being called. In default settings, frameworks like Angular tend to replace index.html with #/my-app-home-page. As a result, the initial page load works fine. However, reloading the page either through code or user actions can cause it to fail and display a blank screen.

To resolve this issue, you need to ensure that /index.html remains in the URL. This can be easily achieved by modifying the base tag:

<base href="./index.html" />

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

Issue with AWS SDK client-S3 upload: Chrome freezes after reaching 8 GB upload limit

Whenever I try to upload a 17 GB file from my browser, Chrome crashes after reaching 8 GB due to memory exhaustion. import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'; import { Progress, Upload } from "@aws-sdk/lib-storage& ...

Having trouble with CSS values not being applied to dynamically injected HTML div elements in Angular 4?

Link to Codepen My Angular calendar application runs smoothly without any errors. However, I am encountering an issue where the CSS styles are not being applied to the page. When I implemented this separately, everything worked fine. But as soon as I inc ...

What is the importance of always catching errors in a Promise?

In my project, I have implemented the @typescript-eslint/no-floating-promises rule. This rule highlights code like this - functionReturningPromise() .then(retVal => doSomething(retVal)); The rule suggests adding a catch block for the Promise. While ...

Leverage the spread operator (or an equivalent method) to transfer all attributes from a solitary mixin

When working with the example below, my goal is to pass only the properties of MyMixedInProps to MyChildComponent using a method similar to the spread operator ({...props}). In my specific scenario, MyMixedInProps is defined in a third-party library (whic ...

Error: Unable to retrieve the value of 'secret' as it is undefined when attempting to assign a response cookie in Express framework

Today's operation that I've carried out countless times seems to be going awry. For some reason, I am unable to set a refresh token cookie using Express. Here is the error message in full /home/me/Code/apGymBE/node_modules/express/lib/response.j ...

Retrieve the route parameters and exhibit the default option in a dropdown menu using Angular 2/4/5, along with translations implemented through ngx-translate

Is there a way to extract route parameters from a URL and then display them in a drop-down menu? I've attempted some solutions using ActivatedRoute, but they are not returning the first value after the base reference. For instance, If the URL is: l ...

NestJS does not recognize TypeORM .env configuration in production build

Currently, I am developing a NestJS application that interacts with a postgres database using TypeORM. During the development phase (npm run start:debug), everything functions perfectly. However, when I proceed to build the application with npm run build a ...

Encountering a cloning error while using React Typescript and React Router DOM when calling props.history.push

When using props.history.push without passing state, everything works perfectly fine. However, when trying to pass data with state, an error occurs. The error message reads: DOMException: Failed to execute 'pushState' on 'History': func ...

Enhance the appearance of the table footer by implementing pagination with Bootstrap Angular6 Datatable styling

I utilized the angular 6 datatable to paginate the data in a table format. https://www.npmjs.com/package/angular-6-datatable Everything is functioning properly, but I am struggling with styling the footer of mfBootstrapPaginator. The items appear stack ...

Recursive array generation

Given an array 'featureList', the goal is to create a new array 'newArray' based on a specific ID. For example, for ID 5, the newArray would be ['MotherBoard','Antenna','Receiver'], where Receiver correspon ...

An object resulting from the combination of two separate objects

After reading a helpful solution on StackOverflow about merging properties of JavaScript objects dynamically, I learned how to utilize the spread operator in Typescript. However, one question still remains unanswered - what will be the type of the object c ...

Angular 8 is throwing a NullInjectorError because it cannot find a provider for AngularFireAnalytics

After running 'npm test', I encountered the following error message: NullInjectorError: StaticInjectorError(DynamicTestModule)[ComparePageComponent -> AngularFireAnalytics]: StaticInjectorError(Platform: core)[ComparePageComponent - ...

Is it possible for a typed function to access object properties recursively?

Is there an efficient method in TypeScript to type a function that can recursively access object properties? The provided example delves two levels deep: function fetchNestedProperty<T, K extends keyof T>(obj: T, prop1: K, prop2: keyof T[K]) { r ...

Issue: Module compilation unsuccessful (from ./node_modules/css-loader/dist/cjs.js) during upgrade from Angular 11 to Angular 16

Summary: Can anyone help with a strange error I encountered while updating my Angular application? Situation: After finally updating my Angular 11 app to Angular 16, I faced several fixable errors along the way. However, one particular error is now hind ...

What is the best way to invoke a method within the onSubmit function in Vuejs?

I am facing an issue with a button used to log in the user via onSubmit function when a form is filled out. I also need to call another method that will retrieve additional data about the user, such as privileges. However, I have been unsuccessful in makin ...

Incorporate a fresh element into an object after its initial creation

Hello, I am looking to create an object in JavaScript that includes an array-object field called "Cities." Within each city entry, there should be information such as the city's name, ID, key, and a District array object containing town data for that ...

Angular 7: Show selected value upon clicking Radio button

I am having an issue with a radio button where I need to display a value when it is clicked. For example, when the "weekly" option is selected, I want it to display "Weekly" in the "Selection" element. I have tried to implement this but it is not working a ...

Ensuring the correct type for an object's interface property value

I am currently working on defining a new interface interface SUser { ID: number; NAME: string; MAIL: string; PASSWORD: string; GENDER: number; BIRTHDATE: string; ID_FB: string; CREDIT: number; ID_REFERRAL: number; } My objective is to c ...

Tips for modifying the width of the mat-header-cell in Angular

Is there a way to customize the mat-header-cell in Angular? I've been trying to change its width without success. Any suggestions would be greatly appreciated. <ng-container cdkColumnDef="name"> <mat-header-cell *cdkHeaderCellDe ...

Ways to link information from one entity to another

Currently, I am utilizing the TMDB API to showcase movies along with their respective genres. In my code, I have two objects where I retrieve details for movies and genres as shown below: listTrendingMovies() { this.listMediaService.listTrendingMovie ...