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
Patricia ArquetteOriginal
2024-12-09 02:21:10370browse

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>

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');

2. Get the iframe's document object:

var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

3. Select the body element within the iframe:

var iframeContent = iframeDocument.getElementById('frameBody');

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

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

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!

Statement:
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
Previous article:Motivational WordsNext article:Motivational Words