Angular 2 provides load event for iframe. So we can detect when new page loaded in iFrame. Normal src attribute of IFrame element gives only initial value. To get latest src URL, we have to use Iframe.contentWindow.location.href
Source Code         DEMO

Markup

myIframe represents iframe element. On load of new page, we are calling onLoadFunc
<iframe #myIframe (load)="onLoadFunc(myIframe)" src="frame2.html"></iframe>

Script - app.component.ts

Observe below onLoadFunc function 
import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: `
  <h4>Detect IFrame Src Change</h4>
  <iframe #myIframe id="myIframe" (load)="onLoadFunc(myIframe)" src="frame2.html"></iframe>
  <h4> Current Source : {{source}}</h4>
  `
})
export class AppComponent {
  source: string = '';

  onLoadFunc(myIframe) {
    this.source = myIframe.contentWindow.location.href;
  }
}

8 comments:

  1. Hey! How can I resolved this error ? 'DOMException: Permission denied to access property "href" on cross-origin object'

    ReplyDelete
    Replies
    1. This happens when your iframe domain and parent document aren't on the same origin (Not using the same protocol, port or domain). it's how modern browsers are built to prevent any malicious activity through iframes. The only way to solve it is to get them on the same domain, use postMessage to send messages between the two frames or proxy the iframe.

      Delete
    2. How did you resolved this error ? 'DOMException: Permission denied to access property "href" on cross-origin object'

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

    currURL: SafeUrl;
    constructor(private translate: TranslateService, private sanitizer: DomSanitizer) {
    }

    this.currURL = this.sanitizer.bypassSecurityTrustResourceUrl(video.url);

    ReplyDelete
  4. How did you resolved this error ? 'DOMException: Permission denied to access property "href" on cross-origin object'

    ReplyDelete

Blogroll

Popular Posts