I have an iframe in my Angular app. The iframe has an image in base64 format. Now I am trying to get that image’s base64 code and store it in a variable in the parent page/Angular app. Can anyone assist, please? I found this article
How to get data from Iframe with Angular 6
Here is my HTML code for the iframe
<iframe src="http://eohdigitalappstore.co.za/test/test.html"></iframe>
I managed to get a bit further by being able to get elements in the iframe page but am now trying to get to the image in the elements tree
const doc = this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentWindow;
console.log(doc.body);
I can get to point in the HTML elements tree which looks like below
Use a view child, it will give you ElementRef
from which you can access a nativeElement
object exactly same as you have it in a normal JavaScript application.
Example (source):
import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
@ViewChild('iframe') iframe: ElementRef;
ngAfterViewInit() {
const nativeEl = this.iframe.nativeElement;
if ( (nativeEl.contentDocument || nativeEl.contentWindow.document).readyState === 'complete' ) {
nativeEl.onload = this.onIframeLoad.bind(this);
} else {
if (nativeEl.addEventListener) {
nativeEl.addEventListener('load', this.onIframeLoad.bind(this), true);
} else if (nativeEl.attachEvent) {
nativeEl.attachEvent('onload', this.onIframeLoad.bind(this));
}
}
}
onIframeLoad() {
const base64String = this.iframe.nativeElement.contentWindow.document.body.innerHTML;
console.log(this.iframe.nativeElement.contentWindow.document.body.children[1].currentSrc);
}
}
Additional interesting readings: https://aakashgoel.com/capturing-the-load-event-of-an-iframe-a-case-study-1a3761c871fe
Note: All this is possible if you observe the same-origin policy.