简体   繁体   中英

How to trigger click event from inside iframe element using angular2

In my code snippet i have one iframe which loads another url. From this i need to trigger a method at outside of iframe based on clicking the button from inside iframe using angular2. Also need to get the data from inside iframe. Can anyone provide a solution to achieve this.

Use postMessage

app.component.ts

import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';

@Component({
  selector: 'ncs-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  src;   
  constructor() { 
    //Yes, is  the same page.
    this.src = this.sanitizer.bypassSecurityTrustResourceUrl('http://localhost:4201');    
    //listen for post messages for this url
    window.addEventListener('message', this.receiveMessage, false);
  }

  receiveMessage(event) {
    console.log(event);
  }

  click() {
    //post message to http://localhost:4201
    window.postMessage('asdasd', 'http://localhost:4201');
  }
}

app.component.html

<button class="button" (click)="click()" >

</button>
<iframe #iframe id="tcsFrame"
        [src]="src"
        scrolling="no"
        frameBorder="0"
        width="100%"
        height="32000px"
        type='text/html'>
</iframe>

If you have control over the content in the iframe you can use window.opener to get to the original window. So what you can do is following:

  1. You register a function on the window object of your angular app.
  2. You use window.opener in the iframe to call said callback.

1. Register function

Somewhere in your angular code you need to register a callback function on the window object:

// Run this method to setup the iframe callback
setupCallback() {
    window.iframeCallback = (param: any) => this.actualCallback(param);
}

// This method will be executed when you
actualCallback(param: any) {
    console.log('Callback executed:', param);
}

2. Call the function from your iframe

Then in your iframe you can use following javascript:

window.opener.iframeCallback('Hello World');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM