我正在Ionic 3中使用iframe在父子之间传递数据。
点击按钮后,我可以使用 iframe.contentWindow.postMessage('value','*')
,但每次单击按钮时,iframe都会刷新。
我执行以下操作:
离子3 html代码 /home.html
<button ion-button id="message_button" (click)="sendMessage()">My iframe</button>
<iframe id="the_iframe" #iframe height="100%" width="100%" [src]="urlpaste()" name="iframe_a"></iframe>
离子3打字稿代码 /home.ts
import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import { DomSanitizer} from '@angular/platform-browser';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
@ViewChild('iframe') iframe: ElementRef;
myIframe:any;
constructor(public navCtrl: NavController, private sanitizer: DomSanitizer) {}
urlpaste(){
this.url = "http://localhost:5000/iframe.html";
return this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
}
ngAfterViewInit() {
this.myIframe = this.iframe.nativeElement.contentWindow
}
sendMessage() {
var random = Math.random();
this.myIframe.postMessage(random, '*');
}
}
纯HTML代码 /iframe.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>iframe Window</title>
<style>
body {
background-color: #D53C2F;
color: white;
}
</style>
</head>
<body>
<h1>Hello there, i'm an iframe</h1>
<p>Send Message: <button id="message_button">Hi parent</button></p>
<p>Got Message:</p>
<div id="results"></div>
<script>
// addEventListener support for IE8
function bindEvent(element, eventName, eventHandler) {
if (element.addEventListener) {
element.addEventListener(eventName, eventHandler, false);
} else if (element.attachEvent) {
element.attachEvent('on' + eventName, eventHandler);
}
}
// Send a message to the parent
var sendMessage = function (msg) {
// Make sure you are sending a string, and to stringify JSON
window.parent.postMessage(msg, '*');
};
var results = document.getElementById('results'),
messageButton = document.getElementById('message_button');
// Listen to messages from parent window
bindEvent(window, 'message', function (e) {
results.innerHTML = e.data;
});
// Send random message data on every button click
bindEvent(messageButton, 'click', function (e) {
var random = Math.random();
sendMessage('' + random);
});
</script>
</body>
</html>
答案 0 :(得分:0)
我有点晚了。但这肯定会在将来对某人有所帮助。
HTML
<iframe id="the_iframe" #iframe height="100%" width="100%" [src]="url" name="iframe_a"></iframe>
TS
url = "";
constructor(public navCtrl: NavController, private sanitizer: DomSanitizer) {
this.url = this.urlpaste();
}
urlpaste(){
let url = "http://localhost:5000/iframe.html";
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
您必须在iframe src中使用“ url”变量。不要在那里直接工作...