4

I'm developing a SPA using angular. When the history back button is pressed, the browser changes only the Youtube iframe and not the entire page, I need to press 2 times the back button to go in the full previous page (at the first time the URL is not updated). This happens only when following 2 links with the same route involving the YT iframe element. I need to keep history navigation, so I can't only delete history elements

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>
Ploppy
  • 14,810
  • 6
  • 41
  • 58
Forno96
  • 61
  • 1
  • 6
  • Why not accept my answer which was posted 13 hours earlier and was the solution to your problem? – Ploppy Feb 10 '19 at 14:20

3 Answers3

6

You don't need to set "src" in the subscribe, you need to replace url:

.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>
gfdevelop
  • 187
  • 2
  • 7
1

One solution is to replace the current URL, this way the iframe is no affected by the browser's back button.

HTML template:

<iframe #iframe></iframe>

TypeScript:

@ViewChild("iframe") iframe: ElementRef;

setUrl(url: string){
  this.iframe.nativeElement.contentWindow.location.replace(myUrl);
}
Ploppy
  • 14,810
  • 6
  • 41
  • 58
0

I know this question has already been answered, but I solved it using as below:

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

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

The pipe safeHtml just return:

    constructor(private sanitizer: DomSanitizer) {
    }

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