Issue with navigating history back in Angular 7 using an iframe

I'm currently working on a single-page application using Angular. I encountered an issue where, when the user presses the browser's back button, only the YouTube iframe content updates and not the entire page. This results in having to press the back button twice to navigate back to the previous page completely. The URL is also not updated on the first press of the back button. This behavior occurs only when navigating through two links with the same route that involve the YouTube iframe element. Deleting history elements is not an option as I need to maintain the history navigation.

Component
export class PlayerComponent implements OnInit {
  videoName: string;
  videoUrl: any;

  constructor(
    private sanitizer: DomSanitizer,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.route.params.subscribe( params => {
      this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl('https://www.youtube.com/embed/' + params.videoId);
    });
  }
}

HTML
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item border border-primary" *ngIf="videoUrl"
    [src] = "videoUrl"
    allowfullscreen>
  </iframe>
</div>

Answer №1

If you're using the subscribe method, make sure to replace the URL instead of setting it as "src":

.ts

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

ngOnInit() {
    this.route.params.subscribe( params => {
        this.iframe.nativeElement.contentWindow.location.replace('https://www.youtube.com/embed/' + params.videoId);
    });
}

@ViewChild("iframe") iframe: ElementRef;

.html

  <iframe #iframe class="embed-responsive-item border border-primary" *ngIf="videoUrl"
    src="about:blank"
    allowfullscreen>
  </iframe>

Answer №2

To prevent the iframe from being affected by the browser's back button, one solution is to update the current URL with a new one.

Here is an example of how this can be implemented using HTML and TypeScript:

<iframe #iframe></iframe>

TypeScript code snippet:

@ViewChild("iframe") iframe: ElementRef;

setUrl(url: string){
  this.iframe.nativeElement.contentWindow.location.replace(myUrl);
}

Answer №3

Although this question may have been previously answered, I managed to solve it using the following method:

  <div class="advertising" [innerHTML]="htmlValue() | safeHtml">
  </div>

  htmlValue() {
    return `
      <iframe src=" + this.iframeUrl() + " frameborder='0' scrolling='no' allow='autoplay'>
      </iframe>
    `;
  }

The safeHtml pipe simply returns:

    constructor(private sanitizer: DomSanitizer) {
    }

    transform(value) {
        return this.sanitizer.bypassSecurityTrustHtml(value);
    }

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

"Ensure that a directive is universally accessible throughout an angular2 final project by registering it

I have created a custom directive that I want to use throughout my application. How can I register my directives so they are accessible in the entire application? I have found outdated solutions for this issue and need a solution specific to Angular 2 fina ...

Looking for an Ionic 3 search function to filter a JSON array?

I am currently developing a market app using ionic 3, and one of the key features is the "products" list. Instead of manually inputting data, my "products page" retrieves items from a JSON array through an HTTP post request: postProducts(type){ return th ...

Exploring the process of linking MatPaginator to a server-sourced datasource within an Angular Material table

In my Angular 5 project, I am utilizing Angular Material table to create a grid. The data is fetched from an HTTP request and stored in a variable named dataSourceNew within the view.ts file. Since dataSourceNew has dynamic content and structure, no interf ...

Is the child component in Angular re-rendered or re-initialized?

Recently started working with Angular(14) and encountered a problem. Whenever I update a property of the parent component, which is an array, the child component gets re-initialized (running the ngOnInit function). This issue arises when using the child co ...

What is the best way to set up role redirection following a successful login within my MEAN stack application?

I have successfully developed a MEAN stack application with a functioning backend and frontend. However, I am looking to enhance it further by implementing role-based redirection after login. There are 5 roles in the system: admin, teacher, nurse, sportsma ...

Discovering how to properly run tests on a function within an if statement using Jasmin, Karma

I've recently started unit testing and I'm facing an issue with my component. The component calls a service to display a list of students. getListStudents() { this.noteService.getStudents({}).subscribe(res => { this.students= res })} Then ...

Incorporating an Angular 2 Directive within the body tag of an

My goal is to create a custom directive that can dynamically add or remove a class from the body element in HTML. The directive needs to be controlled by a service, as I want to manage the visibility of the class from various components. Question: How ca ...

Extending Interfaces Using Keys from an Array in Typescript

When dealing with a scenario where you want a pointfree omit, you can achieve this: type PlainObject<T> = {[key: string]: T} const omit = <K extends string>( name: K ) => <T, U extends PlainObject<T> & { [P in K]: T }>( ...

A guide to building a versatile component using Ionic 3 and Angular 4

I decided to implement a reusable header for my app. Here's how I went about it: First, I created the component (app-header): app-header.ts: import { Component } from '@angular/core'; @Component({ selector: 'app-header', te ...

Configuring ESLint, Prettier, and TypeScript in React Native: A Step-by-Step Guide

Could you provide guidance on setting up ESLint, Prettier, and TypeScript in React Native? I'm currently using absolute paths to specify components. Can you confirm if this setup is correct? tsconfig { "extends": "@tsconfig/react-n ...

The Sequence of Import Statements in Angular 2

The Angular Style Guide provides recommendations on Import line spacing: It is suggested to include one empty line between third-party imports and application imports. Consider arranging import lines in alphabetical order based on the module. For destruc ...

Is it possible for Typescript to automatically infer object keys based on the value of a previous argument?

Currently, my goal is to create a translation service that includes type checking for both tags and their corresponding placeholders. I have a TagList object that outlines the available tags along with a list of required placeholders for each translated st ...

"Exploring the Directionality Possibilities in IONIC 4: L

Currently, I am utilizing ngx-translate within my Ionic 4 project to incorporate multiple languages. Among the languages supported is Arabic and the functionality of ngx-translate works seamlessly by dynamically changing the dir attribute for the HTML tag. ...

retrieve the state property from NavLink

I am encountering an issue with passing objects through components in my project. Specifically, I have a chat object within a component that defines a NavLink. When a user clicks on the ChatsElement, which is a link, the page navigates to the URL /friends/ ...

Angular EventEmitter coupled with Callbacks

In order to create a custom button component for my angular application and implement a method for click functionality, I have the following code snippet: export class MyButtonComponent { @Input() active: boolean = false; @Output() btnClick: EventEmit ...

Ways to incorporate environment variable in import statement?

In my Angular v5 project, I have a situation where I need to adjust the import path based on the environment. For example, I have an OwnedSetContractABI file located in different folders for each environment - dev and production. In dev environment, the ...

Cannot compile Angular 4 Material table: Encountering unexpected closing tag

Currently, I am working on an Angular 4 Project that involves using Material. The main task at hand is to implement a table from Angular Material. However, the issue I am facing is that the table does not compile as expected. Here's the HTML code sni ...

"Encountering a TypeScript error when using React Query's useInfiniteQuery

I am currently utilizing the pokeApi in combination with axios to retrieve data import axios from 'axios' export const fetchPokemonData = async ({ pageParam = "https://pokeapi.co/api/v2/pokemon?offset=0&limit=20" }) => { try ...

List in Angular remains empty

I am facing an issue with populating a simple HTML list using Angular. The problem arises when trying to display the data in the list. When I use console.log("getUserCollection() Data: ", data);, it shows an array which is fine, but console.log("getUser() ...

When I try to integrate Three.js into my React application, it mysteriously causes my root HTML element

While attempting to utilize Three.js in Typescript react, I successfully rendered a Dodecahedron figure along with random stars. However, my intention was to incorporate some markup into my Three.js scene using React. Unfortunately, when I render the Three ...