在角度6中获取IFrame img [英] Get IFrame img in angular 6
问题描述
我的Angular应用中有一个iframe. iframe具有base64格式的图像.现在,我尝试获取该图像的base64代码,并将其存储在父页面/Angular应用程序的变量中.有人可以帮忙吗?我找到了这篇文章
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
这是我的iframe HTML代码
Here is my HTML code for the iframe
<iframe src="http://eohdigitalappstore.co.za/test/test.html"></iframe>
通过设法在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);
我可以指向下面的HTML元素树
I can get to point in the HTML elements tree which looks like below
推荐答案
使用视图子级,它将为您提供ElementRef
,您可以从中访问nativeElement
对象,该对象与普通JavaScript应用程序中的对象完全相同
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.
示例(源):
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);
}
}
其他有趣的读物: 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.
这篇关于在角度6中获取IFrame img的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!