Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger "click" event in iframe

Is it possible to trigger a click event in cross domain iframe with javascript or jquery?

<html>
<head>...</head>
<body>
    <div id='divA'>
        <button type='button' id='buttonA'>Button</button>
    </div>
    <div id='divB'>
        <iframe name='random'>
            <div role='button' id='buttonB'></div>
        </iframe>
    </div>
</body>

</html>

Example : Trigger click event on div(#buttonB) when user click "buttonA"

like image 641
Nw Staff Avatar asked Jan 07 '20 05:01

Nw Staff


2 Answers

You cannot detect click event in cross-domain iframe but one way is that you can detect focus on that iframe.

First click outside of iframe and then on iframe! You will see the alert.

window.focus(); //force focus on the currenct window;
window.addEventListener('blur', function(e){
    if(document.activeElement == document.querySelector('iframe'))
    {
        alert('Focus Left Current Window and Moved to Iframe / Possible click!');
    }
});
<iframe name='random'>
    <div role='button' id='buttonB'></div>
</iframe>
like image 152
Bhavik Kalariya Avatar answered Oct 31 '22 14:10

Bhavik Kalariya


You cannot detect click event in cross-domain iframe but one way is that you can detect focus on that iframe.

First click outside of iframe and then on iframe! You will see the alert.

window.focus(); //force focus on the currenct window;
window.addEventListener('blur', function(e){
    if(document.activeElement == document.querySelector('iframe'))
    {
        alert('Focus Left Current Window and Moved to Iframe / Possible click!');
    }
});
<iframe name='random'>
    <div role='button' id='buttonB'></div>
</iframe>
like image 2
Pushprajsinh Chudasama Avatar answered Nov 15 '22 01:11

Pushprajsinh Chudasama