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

Bring in all Functions and Interfaces from the Types Definition

How can I call the function below in TypeScript: nlp.text("Hi Dr. Miller the price is 4.59 for the U.C.L.A. Ph.Ds.").sentences.length // 1 To make this function call work, what would be the correct import statement needed from this types definition? It& ...

Using ngFor to create dynamic columns in a Kendo Grid

Looking at this code snippet <kendo-grid-column title="{{localizationKeys.adempimenti.organizzazione.responsabile}}" field="addettiGrid"> <li *ngFor="let addetto of addettiGrid; let i=index"> <div>{{addetto}}</div> ...

Trigger a change event for a Material Checkbox by referencing its unique identifier

<div *ngFor="let cus of deselectedList | keyvalue" (click)="clickCheckBox('customer_'+cus.key+'_checkbox')"> {{cus.key}} <mat-checkbox id="customer_{{cus.key}}_checkbox" (change ...

Creating a dynamic return statement in typescript: A step-by-step guide

I am looking to dynamically set a return value to a variable based on values retrieved from an API. The current function in question uses static values: this.markDisabled = (date: NgbDate) => { return (this.calendar.getWeekday(date) !== 5 && ...

Issues with Webpack and TypeScript CommonsChunkPlugin functionality not functioning as expected

Despite following various tutorials on setting up CommonsChunkPlugin, I am unable to get it to work. I have also gone through the existing posts related to this issue without any success. In my project, I have three TypeScript files that require the same ...

Tips for utilizing the forEach method in Angular 2 without relying on ngFor?

I recently started learning Angular 2 and I am trying to figure out how to access array details using a forEach loop and apply certain conditions on it. Once I make the necessary changes, I want to display this data using ngFor. In Angular 1, this was ea ...

Exploring the functionality of Kendo Grid within an Angular application

Currently, I am facing some challenges while trying to execute my Karma tests using the kendo grid within a fresh Angular project. The specifications for this specific component are outlined below: import { async, ComponentFixture, TestBed } from '@a ...

transferring libraries via functions in TypeScript

As I work on developing my app, I have decided to implement the dependency-injection pattern. In passing mongoose and config libraries as parameters, I encountered an issue with the config library. Specifically, when hovering over config.get('dbUri&ap ...

Unable to trigger click or keyup event

After successfully implementing *ngFor to display my data, I encountered an issue where nothing happens when I try to trigger an event upon a change. Below is the snippet of my HTML code: <ion-content padding class="home"> {{ searchString ...

What is the process for invoking a service from a component?

I'm currently facing an issue with my service that is responsible for making HTTP requests and returning responses. The problem arises when I try to display parts of the response on the screen within my component, as nothing seems to be showing up des ...

Determine the sum of exported identifiers based on ESLint rules

Currently, I am facing a requirement in my JavaScript/TypeScript monorepo to ensure that each library maintains a minimal amount of exported identifiers. Is there any existing eslint rule or package available that can keep track of the total number of exp ...

Delete a specific element from an array using a specified criteria

I'm attempting to remove a specific item from an array based on the selected option. To better understand, take a look at this code: component.html <fnd-extended-select label="Tipo Prodotto:" [(ngModel)]="landingType" name="tipoprodotto"> ...

Angular 2 failing to recognize service variable changes initiated from component

Hello there, I'm currently facing a challenge with updating my component to reflect the correct value of a service variable whenever it changes. Here's what I have so far: Snippet from Component1 HTML {{icons | json}} Component1 Code icons: ...

Can you input a string into a generic in TypeScript and subsequently utilize it as a type/interface key?

I had high hopes for achieving this, but unfortunately it's a no-go: type MyType< T extends {}, K extends string = 'keyName' > = T & { [K]: { value: string } }; The error states that a computed property name in a typ ...

What is the solution to the error message stating that the property 'pipe' is not found on the OperatorFunction type?

I implemented the code based on RxJS 6 documentation while working with angular 5, RxJS 6 and angularfire2 rc.10. However, I encountered the following error: [ts] property 'pipe' does not exist on type 'OperatorFunction<{}, [{}, user, str ...

The function doc.fromHTML is not recognized in Angular 6

I am having trouble exporting an HTML template to a PDF using the jsPDF library with Angular. I keep getting the error message "doc.fromHTML is not a function." import { Component, ViewChild, ElementRef } from '@angular/core'; import * as jsPDF ...

Scrolling with React Event

I am attempting to create a scrollbar that only appears when I scroll within a particular area using React. I am utilizing debounce and useState in my implementation. The issue: When I reach the end of the scroll, the event continues to repeat indefinitel ...

What steps should be followed in order to generate a child or item with no assigned key

Here is my TypeScript code designed to automatically record the time of data creation: import * as functions from 'firebase-functions'; export const onAccCreate = functions.database .ref('/Agent/{AgentID}') .onCreate((snapshot, contex ...

Utilizing Typescript for Axios Response

Incorporating Typescript into my project, I encountered a tedious issue while making an API call using axios. The problem lies within handling nested data properly. Despite my belief that I have correctly typed everything, I persistently face a Typescript ...

How can one utilize JSON.parse directly within an HTML file in a Typescript/Angular environment, or alternatively, how to access JSON fields

Unable to find the answer I was looking for, I have decided to pose this question. In order to prevent duplicates in a map, I had to stringify the map key. However, I now need to extract and style the key's fields in an HTML file. Is there a solution ...