Angular 9: Encountered an Uncaught DOMException while attempting to access a blocked frame from a

Recently, I implemented a sign-in authentication feature for my Angular application and decided to test it out. The sign-up process worked perfectly fine. However, upon signing out and attempting to sign back in, the header failed to update as expected. Instead, I encountered an error in the console:

Uncaught DOMException: Blocked a frame with origin "chrome-extension://hdokiejnpimakedhajhdlcegeplioahd" from accessing a cross-origin frame. at e [as constructor] (chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/lpfulllib.js:1:1441712) at new e (chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/lpfulllib.js:1:1444920) at chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/lpfulllib.js:1:1461728

Despite the GET request being successful, the response indicated that I was not authenticated:

{authenticated: false, username: null}
authenticated: false
username: null

This was confusing because the request was supposed to be a POST, not a GET. Why did it interpret it as a GET request?

My signin() method within the authentication service clearly specifies that it should be a POST request:

signin(credentials: SigninCredentials) {
    return this.http.post(this.rootUrl + "/auth/signin", credentials).pipe(
      tap(() => {
        this.signedin$.next(true);
      })
    );
  }

Below is the code for my auth HTTP interceptor:

import { Injectable } from "@angular/core";
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpEventType,
} from "@angular/common/http";
import { Observable } from "rxjs";

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    // Modify or log the outgoing request
    const modifiedReq = req.clone({
      withCredentials: true,
    });

    return next.handle(modifiedReq);
  }
}

I don't believe the issue lies within my AuthHttpInterceptor; rather, I suspect there might be a problem in the AuthService:

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { BehaviorSubject } from "rxjs";
import { tap } from "rxjs/operators";

interface UsernameAvailableResponse {
  available: boolean;
}

interface SignupCredentials {
  username: string;
  password: string;
  passwordConfirmation: string;
}

interface SignupResponse {
  username: string;
}

interface SignedinResponse {
  authenticated: boolean;
  username: string;
}

interface SigninCredentials {
  username: string;
  password: string;
}

@Injectable({
  providedIn: "root",
})
export class AuthService {
  rootUrl = "https://api.my-email.com";
  signedin$ = new BehaviorSubject(false);

  constructor(private http: HttpClient) {}

  usernameAvailable(username: string) {
    return this.http.post<UsernameAvailableResponse>(
      this.rootUrl + "/auth/username",
      {
        username,
      }
    );
  }

  signup(credentials: SignupCredentials) {
    return this.http
      .post<SignupResponse>(this.rootUrl + "/auth/signup", credentials)
      .pipe(
        tap(() => {
          this.signedin$.next(true);
        })
      );
  }

  checkAuth() {
    return this.http
      .get<SignedinResponse>(this.rootUrl + "/auth/signedin")
      .pipe(
        tap(({ authenticated }) => {
          this.signedin$.next(authenticated);
        })
      );
  }

  signout() {
    return this.http.post(this.rootUrl + "/auth/signout", {}).pipe(
      tap(() => {
        this.signedin$.next(false);
      })
    );
  }

  signin(credentials: SigninCredentials) {
    return this.http.post(this.rootUrl + "/auth/signin", credentials).pipe(
      tap(() => {
        this.signedin$.next(true);
      })
    );
  }
}

Answer №1

It appears that there are no HttpHeaders present in your setup. Based on my observations, it seems like a configuration error is causing the exception.

You can enhance your Angular interpector with the following code snippet:

import {
  HttpEvent,
  HttpHandler,
  HttpHeaders,
  HttpInterceptor,
  HttpRequest,
} from '@angular/common/http'
import { Injectable } from '@angular/core'
import { Observable } from 'rxjs'

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // const token = localStorage.getItem('access_token')
    // const userToken = localStorage.getItem('id_token')

    if (token) {
      const authRequest = req.clone({
        setHeaders: {
          'Content-Type': 'application/json',
         // Authorization: `Bearer ${token}`,
         // userID: `${userToken}`,
        },
      })
      return next.handle(authRequest)
    } else {
      const headers = new HttpHeaders({
        'Content-Type': 'application/json',
      })
      const cloned = req.clone({
        headers,
      })
      return next.handle(cloned)
    }
  }
}

Additionally, ensure that your backend system is properly configured and that headers like Access-Control-Allow-Origin are set to true.

Answer №2

The issue stems from the LastPass extension. To resolve it, simply disable the extension and the error should no longer be present.

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 encountered while accessing theme properties in a ReactJs component with Typescript

I am trying to pass the color of a theme to a component in my TypeScript project (as a beginner). However, I have encountered an error that I am struggling to resolve. The specific error message reads: 'Parameter 'props' implicitly has an ...

Error: The mongoose initialization is preventing access to the 'User' variable

this issue arises in mongoose Cannot access 'User' before initialization at order.model.js:6:52 even though User is already defined order.js import mongoose from 'mongoose'; import Product from './product.model.js'; import U ...

What is the best way to retrieve information from an http website and display it in an html table using javascript

I am attempting to retrieve data from the specified site: . The website appears to feature a list of objects, and my goal is to extract each object enclosed in {} into separate columns within a row (6 columns total - one for gameNumber, one for teams, and ...

Interactive feature allowing all embedded YouTube videos on a webpage to play synchronously, with sound disabled, and on a continuous loop

I am in the process of developing a button that, when clicked by a user, will trigger all embedded YouTube videos on a specific webpage to start playing simultaneously, with sound muted, and set to loop. The target page for this button implementation can ...

Font family 'anticon' is not recognized

While following a coding tutorial on YouTube, I encountered an error message that has me stumped. Despite having the correct import statement and dependency installed, the issue persists. Error message in iOS simulator: https://i.stack.imgur.com/LOVCQl. ...

Step-by-step guide on entering text into a hidden field with Selenium WebDriver and Java

I am currently utilizing WebDriver in conjunction with Java for automated testing. I have come across a hidden input field within the following HTML code: <input type="hidden" value="" name="body" id=":6b"> My challenge lies in trying to input data ...

Is there a way to address an ajax post issue where I need to post a variable but only have one js file?

On my website, I have the following code where each add-to-favor- is associated with a unique hash to differentiate between multiple results. <a class="btn btn-default btn-sm m-t-10 add-to-favor-'.$active[hash].'"> <i class="text-da ...

Experiencing CORS (Cross-Origin Resource Sharing) issue while utilizing Python Flask-Restful in conjunction with consuming AngularJS (specifically with $

Currently, I am using a Python program in conjunction with the flask-restful extension to provide a restful service. My goal is to consume this service with an AngularJS app. So far, everything is functioning properly on my localhost. However, whenever I m ...

Using JavaScript to Detect Asynchronous Postbacks in ASP.NET AJAX

Seeking advice on the JavaScript code required to determine if an asynchronous postback is in progress. Can anyone help with this? Appreciate any assistance. ...

Transferring data from PHP to AJAX and then injecting it into an SQL query

I've been attempting to pass a datepicker variable into an onclick ajax function, which then sends it to another ajax method that passes the variable to an SQL query. The result of the query is then passed back into the ajax function to generate a cha ...

Growing the number of items in the shopping cart

I am facing challenges in adjusting the quantities of products in my cart after adding them. Let me explain the process step by step. 1- I list out the products. 2- I create a function to abbreviate the quantities (miktarKisalt) 3- If the products can b ...

The distinction between storing data and component data becomes apparent when using Vuex in conjunction with a persisted state

Below is my post.js file in the store directory: import axios from 'axios' import createPersistedState from "vuex-persistedstate" export default { namespaced: true, state: { sample_data: 'Welcome!!', l ...

What are the steps to resolve an invalid token error when receiving it? (repl.it)

Today marks my introduction to node.js, recommended by a friend. Due to limited resources, I have opted to utilize repl.it for hosting. However, I am faced with an error in my first attempt at using it. The purpose of my current script is to make my user ...

The actions performed within an event listener function are undone once they have been carried out

I'm a newcomer to Javascript and I am currently experimenting with it. While browsing through a tutorial on w3schools, I came across an example of changing the color of a button after clicking on it. My idea was to take it a step further by loading a ...

How to simultaneously send multiple GET requests in Angular 2

By utilizing a promise JS library (https://github.com/stackp/promisejs), I am able to achieve the following: promise.join([ promise.get('/settings'), promise.get('/translations'), promise.get('/main-data') ]).then ...

Create a JSON array of objects and dynamically append new items to it

I'm feeling a bit lost and frustrated at the moment. I'm attempting to initialize a JSON Array and dynamically add JSON Objects to it during runtime, but something isn't clicking for me. Let's say I receive a list of repeated values fr ...

The error encountered is: `Exception: startDate.getTime is not a valid function

const [currentDate, setCurrentDate] = useState(new Date()); const fetchDataFromAPI = () => { let timeStamp = Number(currentDate.getTime()); axios.get( `https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=BTC,USD,EUR& ...

How to update JSON file on server using JavaScript

I am encountering an issue that has been discussed quite frequently. Despite trying various solutions, none have proven effective so far. The problem lies in my JavaScript file where I have some data that I need to append to an existing .json file on my s ...

JavaScript Plugins for Cordova

The more I delve into the inner workings of Cordova, the clearer it becomes to me. Yet, one area that continues to perplex me is the structure of JavaScript plugins. Typically, I write my JavaScript code as follows, adhering to what I believe is the stand ...

Avoid reloading the page when submitting a form using @using Html.BeginForm in ASP.NET MVC

I have a webpage featuring a model that needs to be sent to the controller along with additional files that are not part of the model. I have been able to successfully submit everything, but since this is being done in a partial view, I would like to send ...