Home > Web Front-end > JS Tutorial > How Can I Access the InnerHTML of an Iframe Using Pure JavaScript?

How Can I Access the InnerHTML of an Iframe Using Pure JavaScript?

Patricia Arquette
Release: 2024-12-09 02:21:10
Original
376 people have browsed it

How Can I Access the InnerHTML of an Iframe Using Pure JavaScript?

Accessing the Inner Contents of an iframe in JavaScript

In HTML, an iframe element embeds another webpage within its own document. To interact with the contents of the embedded page, the parent document needs to access its body's content.

Consider the following iframe:

<iframe>
Copy after login

The goal is to retrieve the text "test
" from the iframe.

Pure JavaScript Solution

To access the iframe's body content in pure JavaScript, use the following techniques:

1. Obtain the iframe element:

var iframe = document.getElementById('id_description_iframe');
Copy after login

2. Get the iframe's document object:

var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
Copy after login

3. Select the body element within the iframe:

var iframeContent = iframeDocument.getElementById('frameBody');
Copy after login

4. Access the innerHTML of the body element to obtain the content:

var iframeBodyContent = iframeContent.innerHTML; // "test<br/>"
Copy after login

Additional Notes:

  • This solution requires the same-origin policy to be observed.
  • Consider using cross-domain messaging or CORS if the iframe is from a different domain.
  • This technique not only allows you to retrieve the body's content but also select and manipulate elements within the iframe.

The above is the detailed content of How Can I Access the InnerHTML of an Iframe Using Pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template