access iframe from web page

How to Access Iframe Content With JavaScript

Iframe provides an easy way to embed other documents and web pages within the current HTML document. It is commonly used to display ads, videos and other interactive content on website. However, often you may need to access iframe content on your web page. In this article, we will learn how to access iframe content with JavaScript.


How to Access Iframe Content With JavaScript

You may want to access iframe content in order to manipulate it. Here are the steps to access iframe content with JavaScript.

Let us say you have the following iframe.

<iframe src="https://www.example.com" id='myFrame'></iframe>

The above iframe tag will load the page from www.example.com. Let us say it has an element with id=myDiv.

If both the iframe and the HTML page where it is included are from same domain (e.g. example.com) then you can easily access this div using the following code. Here is a jQuery code to access the iframe with id=’myFrame’ and then access the div with id=’myDiv’. jQuery provides contents() function that allows you to access the iFrame elements using identifiers, if both the iframe and page are on the same domain. Once you are able to access the iFrame element, you can call other jQuery functions on it, such as removeClass().

$("#iFrame").contents().find("#myDiv").removeClass("hidden");

If you want to use plain JavaScript for this purpose, you can use the following code to access the document loaded in iFrame.

 document.getElementById('myframe').contentWindow.document

Please note, the above code works only if both the iframe calls a page from the same domain as your HTML page that contains iframe. If they are both different domains, then you will most likely get an error in browser, saying permission denied. This type of error occurs because the HTML document and the page within iframe have different origins and cross origin requests are blocked by browsers.

In such cases, you need to modify your website’s server code to allow cross origin requests.

In this article, we have learnt how to access iframe elements from an HTML page where it is included.

Also read:

How to Convert Form Data to JSON in JavaScript
How to Check if Element is Visible After Scrolling
How to Use Variable in Regex in JavaScript
How to Use Variable in Regex in Python
How to Split Array into Chunks in JavaScript

Leave a Reply

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