【发布时间】:2019-03-25 11:49:39
【问题描述】:
我在 Angular 4 应用程序中将 iframe 与其他域一起使用,并希望在 iframe 表单输入字段中分配值。
我们有什么办法可以做到这一点??
谢谢。
【问题讨论】:
我在 Angular 4 应用程序中将 iframe 与其他域一起使用,并希望在 iframe 表单输入字段中分配值。
我们有什么办法可以做到这一点??
谢谢。
【问题讨论】:
我之前也遇到过类似的问题:我认为在这种情况下,你需要做两件事:
如果应用程序位于不同的域中,则它们无法直接交互,因为Same-origin policy.
要实现这一点,您必须使用 window.postMessage()。
基本思路:
iframe 应用使用window.addEventListener("message", receiveMessage, false);订阅消息
嵌入应用程序通过 iframe 发送消息,例如 @ViewChild('iframeRef') iframeRef: ElementRef;
this.iframeRef.nativeElement.contentWindow.postMessage({some message object to the iframe}, '*', []);
注意:出于安全考虑,您可能想检查消息事件的来源,并且只处理您信任的来源发送的消息。
function receiveMessage(event){
console.log("Received a message From: Angular", event);
// if (event.origin !== "http://example.org:8080")
// return;
// todo: this is crucial for being secure!
....
}
【讨论】: