Triggering a Click Event on a Third-Party iframe element using jQuery

Interacting with third-party iframes can be quite challenging due to the security restrictions enforced by browsers. However, there are scenarios where you might want to trigger a click event on an element within a third-party iframe. This blog post will guide you through the process using jQuery, while adhering to best practices and ensuring security.

Understanding the Challenges

The main challenge with interacting with third-party iframes is the same-origin policy. This policy prevents scripts on one origin from accessing data on a different origin, which includes manipulating the DOM of an iframe that comes from a different origin.

Goal to trigger a button or element of iframe 

In my case  I want to make a jQuery click event,  where an anchor tag on my website is clicked then it should trigger a button of iframe. After spending some time over the internet I found a working solution that I want to share with you.

I am assuming you have an HTML page that contains an anchor tag or any element that needs to be clicked and on its click will trigger the iframe button.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Trigger Click Event in Third-Party iframe</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<iframe id="thirdPartyIframe" src="https://example.com/iframeContent.html" width="600" height="400"></iframe>
<a href="#" id="triggerClick">Trigger Click in iframe</a>

<script src="parentScript.js"></script>
</body>
</html>

Create a parentScript.js file in your website folder.

$(document).ready(function() {
$('#triggerClick').on('click', function() {
// Trigger iframe's button
$("#thirdPartyIframe").contents().find('button').click();
return false;
});
});

Uisng this small javascript code can help to trigger the Iframe’s element or button.

I hope it will work for you and if you have any doubt then please connect with me!.

Thanks
Happy Coding

Related Blog

Sign up for our newsletter to stay up to
date with tech news!