Categories
JavaScript Answers

How to expose IFrame’s DOM using jQuery?

Spread the love

Exposing an iFrame’s DOM using jQuery is not directly possible due to security restrictions.

This is because of the Same Origin Policy, which prevents scripts from accessing the contents of an iFrame if it’s loaded from a different domain, protocol, or port than the parent page.

However, if the iFrame source is from the same origin as the parent page, you can manipulate its DOM using jQuery.

To do this we can write:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Parent Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
    // Accessing the iFrame's content
    var iframeDocument = $('#myIframe').contents();

    // Manipulate the iFrame's content using jQuery
    iframeDocument.find('#iframeContent').css('color', 'red');
});
</script>
</head>
<body>
<iframe id="myIframe" src="iframe-content.html"></iframe>
</body>
</html>

In this example, we’re loading an iFrame with the id “myIframe” and setting its source to “iframe-content.html”. This source is assumed to be on the same origin as the parent page.

Inside the jQuery code, we’re accessing the iFrame’s content using $('#myIframe').contents(). This gives us access to the iFrame’s document and allows us to manipulate its DOM.

We then use standard jQuery methods to manipulate the iFrame’s content. In this case, we’re changing the color of an element with the id “iframeContent” inside the iFrame.

Remember, you can only access the iFrame’s content if it’s from the same origin as the parent page.

If the iFrame is from a different origin, you won’t be able to access its DOM due to security restrictions.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *