How to get html from iframe in angular?

Member

by dana , in category: Javascript , 3 months ago

How to get html from iframe in angular?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 3 months ago

@dana 

To get the HTML content from an iframe in Angular, you need to access the contentWindow property of the iframe element and then use the document property of the contentWindow to access the HTML content. Here's an example of how you can achieve this:

  1. First, you need to get a reference to the iframe element in your component template using Angular's @ViewChild decorator. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-iframe',
  template: '<iframe #myIframe></iframe>'
})
export class MyComponent implements AfterViewInit {
  @ViewChild('myIframe') iframe: ElementRef;

  ngAfterViewInit() {
    const iframeContent = this.iframe.nativeElement.contentWindow.document.body.innerHTML;
    console.log(iframeContent);
  }
}


  1. In the ngAfterViewInit() lifecycle hook, you can access the content of the iframe element by using the contentWindow property and then accessing the HTML content using the document property.


Note that accessing the contents of an iframe from a different domain can lead to cross-origin issues. You may need to configure your server to allow cross-origin requests or use a proxy server to work around these issues.