角度2手柄点击iframe

时间:2017-05-29 13:26:50

标签: html angular typescript iframe

有没有办法点击iframe内的链接?

<iframe *ngIf="currentFrameUrl" id="contentFrame" [src]="currentFrameUrl | safe"></iframe>

我的iframe组件只包含一个订阅可观察变量的简单代码。

export class ContentFrameComponent implements OnInit {
    currentFrameUrl: string;
    currentMenuState: boolean;
    @ViewChild('contentFrame') iframe: ElementRef;

    constructor(private frameService: ContentFrameService) {        
      this.currentMenuState = true;      
    }

    ngOnInit(): void {
      this.frameService.providerCurrentUrl$.subscribe(data => this.currentFrameUrl = data);
      this.frameService.providerMenuState$.subscribe(data => this.currentMenuState = data);
    }

    ngAfterViewInit() {
      let doc = this.iframe.nativeElement.contentDocument ||this.iframe.nativeElement.contentWindow;
      if (typeof doc.addEventListener !== undefined) {
        console.log("inside if - addEventListener") // Is shown
        doc.addEventListener("click", this.iframeClickHandler, false)
      } else if (typeof doc.attachEvent !== undefined) {
        console.log("inside if - attachEvent ") // Does not show
        doc.attachEvent("onclick", this.iframeClickHandler)
      }
    }

    iframeClickHandler(): void {
      console.log("Click test") // Does not show
    }
}

我的目标是在iframe链接上捕获点击事件,停止其传播并使用router.navigatelocation.go / location.replaceState设置iframe链接的网址。还不确定哪个选项更好。

我无法控制iframe内加载的网页。我只知道,链接应该包含可以与我的动态路由一起使用的url

3 个答案:

答案 0 :(得分:1)

使用@HostListener('window:blur',['$ event'])装饰器,此装饰器附带的方法在IFrame单击时触发。

  @HostListener('window:blur', ['$event'])
  onWindowBlur(event: any): void {
    console.log('iframe clicked');
  }

注意:这也适用于跨域操作。

答案 1 :(得分:0)

为什么你不能使用简单的onclick?

试试这段代码:

<iframe *ngIf="currentFrameUrl" id="contentFrame" [src]="currentFrameUrl | safe" (onclick)="clicked()"></iframe>

点击

答案 2 :(得分:0)

<iframe *ngIf="currentFrameUrl" id="contentFrame" [src]="currentFrameUrl | safe" #iframe></iframe>

export class ContentFrameComponent implements OnInit {
      currentFrameUrl: string;
      currentMenuState: boolean;
      @ViewChild('iframe') iframe: ElementRef;

      constructor(private frameService: ContentFrameService) {
        this.currentMenuState = true;
      }

      ngOnInit(): void {
        this.frameService.providerCurrentUrl$.subscribe(data => this.currentFrameUrl = data);
        this.frameService.providerMenuState$.subscribe(data => this.currentMenuState = data);
      }

      ngAfterViewInit() {
        let doc = this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentWindow;
        if (typeof doc.addEventListener !== undefined) {
          doc.addEventListener("click", this.iframeClickHandler, false)
        } else if (typeof doc.attachEvent !== undefined) {
          doc.attachEvent("onclick", this.iframeClickHandler);
        }
      }

      iframeClickHandler() {
        alert("Iframe clicked");
      }
    }

注意:这可能不适用于跨域操作。