我的窗口中有一个iframe,我用jquery添加了新的按钮.在迁移到angular2之前,我使用parent.SampleFunction()从iframe调用父代的函数.现在,parent是一个角度组件,它不起作用.
export class AppComponent {
// use jquery to find the iframe and put a button into it
addButtonToIFrame() {
...
let buttonHtml = "<button onClick='parent.SampleFunction()'></button>"
...
}
SampleFunction() {
...
}
Run Code Online (Sandbox Code Playgroud)
}
我该如何更改onclick功能以访问父级?
您可以安全地访问window.parent对象,因此您只需将您SampleFunction置于全局window对象中即可.
export class AppComponent {
constructor(){
(<any>window).SampleFunction= this.SampleFunction.bind(this);
}
// use jquery to find the iframe and put a button into it
addButtonToIFrame() {
...
let buttonHtml = "<button onClick='parent.SampleFunction()'></button>"
...
}
SampleFunction() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
如果您有多个相同类的实例并且您SampleFunction处理组件状态,则可能需要为您创建随机名称SampleFunction.
您也可以使用PostMessageAPI,这应该是一个更灵活的选择.
如果您正在处理来自其他域的iframe,则可以使用PostMessage API:
iframe中的脚本
window.parent.postMessage({foo:"foo"});
Run Code Online (Sandbox Code Playgroud)
父内部的组件
export class AppComponent {
@HostListener("window:message",["$event"])
SampleFunction($event:MessageEvent) {
if (event.origin !== "protocol://my-expected-domain.tdl:port")
return;
console.log($event.data)// {foo:"foo"}
}
}
Run Code Online (Sandbox Code Playgroud)
当然,您必须检查event.originiframe的实际域.
| 归档时间: |
|
| 查看次数: |
3426 次 |
| 最近记录: |