Как найти iframe на сайте js

I have a webpage where there is a textarea within an iframe. I need to read the value of this textarea from its child page using JavaScript.

Presently by using window.parent.getelementbyID().value in the JavaScript, I am able to fetch values of all controls in the parent page except the textarea within the iframe.

Can anyone please give me any pointers to resolve this issue?

danwellman's user avatar

danwellman

9,0198 gold badges59 silver badges87 bronze badges

asked Sep 20, 2009 at 14:57

archana roy's user avatar

5

If your iframe is in the same domain as your parent page you can access the elements using window.frames collection.

// replace myIFrame with your iFrame id
// replace myIFrameElemId with your iFrame's element id
// you can work on window.frames['myIFrame'].document like you are working on
// normal document object in JS
window.frames['myIFrame'].document.getElementById('myIFrameElemId')

If your iframe is not in the same domain the browser should prevent such access for security reasons.

greybeard's user avatar

greybeard

2,1537 gold badges28 silver badges63 bronze badges

answered Sep 20, 2009 at 17:00

RaYell's user avatar

RaYellRaYell

69.4k20 gold badges125 silver badges152 bronze badges

7

window.frames['myIFrame'].document.getElementById('myIFrameElemId')

not working for me but I found another solution. Use:

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')

I checked it on Firefox and Chrome.

answered Dec 23, 2013 at 19:49

2

You should access frames from window and not document

window.frames['myIFrame'].document.getElementById('myIFrameElemId')

nhahtdh's user avatar

nhahtdh

55.8k15 gold badges126 silver badges162 bronze badges

answered Nov 1, 2011 at 17:44

Mena Joseph's user avatar

0

Make sure your iframe is already loaded. Old but reliable way without jQuery:

<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe>

<script>
function access() {
   var iframe = document.getElementById("iframe");
   var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
   console.log(innerDoc.body);
}
</script>

answered Mar 14, 2017 at 9:45

lukyer's user avatar

lukyerlukyer

7,4373 gold badges37 silver badges31 bronze badges

this code worked for me:

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId');

ReactiveRaven's user avatar

answered Oct 28, 2016 at 14:54

Abdelkreem Mostafa Saed's user avatar

Two ways

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')

OR

window.frames['myIFrame'].contentWindow.document.getElementById('myIFrameElemId')

answered Apr 11, 2018 at 9:39

Vlad's user avatar

VladVlad

7,7893 gold badges54 silver badges43 bronze badges

I have a webpage where there is a textarea within a iframe. I need to read the value of this textarea from its child page JavaScript. Presently by using window.parent.getelementbyID().value in the JavaScript, I am able to fetch values of all controls in the parent page except the textarea within the iframe.

The frame id and frame name in my parent page changes in runtime, hence we cannot use the frame id/frame name for reference.

Amir's user avatar

Amir

1,3182 gold badges13 silver badges27 bronze badges

asked Sep 21, 2009 at 4:12

archana roy's user avatar

3

If you have the HTML

<form name="formname" .... id="form-first">
    <iframe id="one" src="iframe2.html">
    </iframe>
</form>

and JavaScript

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

var inside = iframeRef( document.getElementById('one') )

inside is now a reference to the document, so you can do getElementsByTagName('textarea') and whatever you like, depending on what’s inside the iframe src.

Owen Blacker's user avatar

Owen Blacker

4,1172 gold badges33 silver badges70 bronze badges

answered Sep 21, 2009 at 4:20

meder omuraliev's user avatar

meder omuralievmeder omuraliev

183k70 gold badges388 silver badges429 bronze badges

5

Using jQuery you can use contents(). For example:

var inside = $('#one').contents();

answered Jul 3, 2013 at 10:37

Doug Amos's user avatar

Doug AmosDoug Amos

4,2331 gold badge21 silver badges23 bronze badges

1

The aim of this tutorial is to describe and demonstrate using JavaScript to manipulate and interact with iframes, showing how to access and modify properties of the iframe element, how to communicate with the document inside the iframe, getting information from the iframe and passing information to it.

Iframes, or inline frames, allow you to load separate HTML files into an existing document.Iframes can be placed anywhere in the html document.

JavaScript can be used to manipulate the appearance and properties of the iframe element , its position, size, and src, for example. JavaScript can also be used to pass data between the html document containing the iframe and the iframe itself.

1. HTML

First of all you need to create two simple html documents.

iframeExample.html

<!DOCTYPE html>
<html>
<head>
	<title>Javascript IFrame Example</title>
</head>
<body>

</body>
</html>

2. Javascript IFrame Example

2.1 Change iframe src by using javascript

Let us add the following html code to our page.

<div>
	<iframe id="ifrm" src="https://www.webcodegeeks.com/" width="500" height="300"></iframe>
</div>
<div>
	<a href="javascript:retrun 0;" onclick="changeIframePro()">change iframe src</a>
</div>

You can get a reference to an iframe using getElementById(). You can use that reference to set properties on the iframe, such as style,src and so on.

<script type="text/javascript">

function changeIframePro(){
	// reference to iframe with id 'ifrm'
	var ifrm = document.getElementById('ifrm');
	ifrm.src = 'http://www.iliastsagklis.com/'; // set src to new url
}

</script>

The result in the browser would be:

Chnage iframe src by using javascript

Change iframe src by using javascript

2.2 Access to Iframe and its Document and Content

The buttons in the following html code will access the iframe data by using contentWindow and contentDocument properties.

<h1>Accessing an Iframe and its Document and Content</h1>
<p>This example demonstrates the containing document interacting with the iframe.</p>
<form id="demoForm" action="#">
    <p>
        <input name="button1" type="button" value="Button 1" onclick="button1Handler()"/>
        <input name="button2" type="button" value="Button 2" onclick="button2Handler()"/> 
        <input name="button3" type="button" value="Button 3" onclick="button3Handler()"/> 
        <input name="button4" type="button" value="Button 4" onclick="button4Handler()"/> 
    </p>
    <p><input type="text" name="display" size="30" readonly="readonly" /></p>
</form>

<iframe name="ifrm" id="ifrm" src="iframed.html" width="450" height="250"></iframe>

The iframe element provides contentWindow and contentDocument properties. The following JavaScript uses these properties to get references to the iframed document’s window and document objects. Once you have references to the window and document objects, you can access virtually any object or property in the iframed document and can access it’s javascript varibales and methods.

<script type="text/javascript">

    // get reference to the form 
    var form = document.getElementById('demoForm');
    
    // set height of iframe and display value
    function button1Handler(){
        var ifrm = document.getElementById('ifrm');
        var ht = ifrm.style.height = '200px';
        form.display.value = 'The iframe's height is: ' + ht;
    }
    
    // increment and display counter variable contained in iframed document
    function button2Handler() {
        // get reference to iframe window
        var win = document.getElementById('ifrm').contentWindow;
        var counter = ++win.counter; //  increment
        form.display.value = 'counter in iframe is: ' + counter;
    }
    
    // reference form element in iframed document
    function button3Handler() {
        
        var ifrm = document.getElementById('ifrm');
        // reference to document in iframe
        var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
        // get reference to greeting text box in iframed document
        var fld = doc.forms['iframeDemoForm'].elements['greeting'];
        var val = fld.value;
        // display value in text box
        form.display.value = 'The greeting is: ' + val;
    }
    
    function button4Handler(){
        // get reference to iframe window
        var win = document.getElementById('ifrm').contentWindow;
        win.clearGreeting(); // call function in iframed document
    }

</script>

The result in the browser would be:

Access to Iframe and its Document and Content

Access to Iframe and its Document and Content

2.3 JavaScript Interaction between Iframe and Parent

First of all add the following html code to the iframeExample.html page.

<h1>References from Iframed Document to its Parent</h1>
<p>This example demonstrates access from iframed document to containing document.</p>
<iframe name="ifrm" id="ifrm" src="parented.html" width="450" height="250"></iframe>

<form action="#" id="demoForm">
    <label for="greeting">Enter a Greeting: </label>
    <input type="text" name="greeting" id="greeting" value="Hello there!" />
</form>

<script type="text/javascript">
    var counter = 0;
</script>

Create a new page and add following code . parented.html

<form action="#" id="iframeDemoForm">
    <p><input name="button1" type="button" value="Click Me" /> repeatedly to increment global variable in containing document</p>
    <p><input name="button2" type="button" value="Click Me" /> to transfer Greeting below to text box above</p>
</form>

It is simpler to use the parent property to access the containing document. For example, you can reference a form in the containing document,notice line 9 of the following javascript code.

The parent keyword can also be used to access global variables or invoke functions in the main document from the document inside the iframe, as the example below demonstrates.

<script type="text/javascript">

(function() {
    // get reference to form to attach button onclick handlers
    var form = document.getElementById('iframeDemoForm');
    // increment and display counter variable contained in parent document
    form.elements['button1'].onclick = function() {
        parent.counter++;
        var parentCounter = 'counter in parent document is: ' + parent.counter;
        this.form.elements['display'].value = parentCounter;
    }

    form.elements.button2.onclick = function() {
        // get reference to greeting text box in containing document
        var fld = parent.document.forms['demoForm'].elements['greeting'];
        var val = fld.value;
        // display value in iframed document's text box
        this.form.elements.display.value = 'The greeting is: ' + val;
    }
})(); // end remove from global namespace and invoke
</script>

The result in the browser would be:

javascriptIframeExample3

JavaScript Interaction between Iframe and Parent

2.4 Dynamically Generating an Iframe

On this page, JavaScript is used to create an iframe element and insert it into the document. The createElement method is used to dynamically generate the iframe. Either the appendChild or insertBefore method can be used to place the iframe in the document. The setAttribute method can be used to add id, src, and other attributes.Following html and javascript demonstrates the dynamically generating of Iframe.

       <h1>Dynamically Generating an Iframe</h1>
       <p id="marker" class="end">Iframes Examples</p>
<script type="text/javascript">
(function() {
    var ifrm = document.createElement('iframe');
    ifrm.setAttribute('id', 'ifrm');

    // to place before another page element
    var el = document.getElementById('marker');
    el.parentNode.insertBefore(ifrm, el);

    ifrm.setAttribute('src', 'http://www.webcodegeeks.com');
})(); 
</script>

3. Download the Source Code

Photo of Saeb Najim

Saeb has graduated from the University of Technology. During the last ten years (since 2005) he has been involved with a large number of projects about programming, software engineering, design and analysis . He works as a senior Software Engineer in the e-commerce and web development sector where he is mainly responsible for projects based on Java, Java frameworks, design patterns and Big Data technologies.

LoneRay

Нашёл такой код и отредактировал немного, но почему-то содержимое фрейма пусто. Как получить доступ к содержимому фрейма?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
    <iframe src='index.html' id='frame'></iframe>
    <script type='text/javascript'>





document.getElementById("frame").onload = function()
{
    var FRAM = document.getElementById("frame");
    var DOC = FRAM.contentDocument;
	alert(FRAM.contentDocument.getElementById('date'));//выведет Object HTML..
	alert(DOC.getElementById('date'));//выведет NULL(WTF?)

}

    </script>

</body>
</html>


  • Вопрос задан

    более трёх лет назад

  • 5725 просмотров

<html>
<body>
    <iframe src='index.html' id='frame'></iframe>

    <script type='text/javascript'>
        document.getElementById("frame").onload = function () {
            var FRAM = document.getElementById("frame");
            var DOC = FRAM.contentDocument;
            alert(FRAM.contentDocument.body);
        }
    </script>
</body>
</html>

Пригласить эксперта


  • Показать ещё
    Загружается…

20 мая 2023, в 13:50

1500 руб./в час

11 мая 2023, в 16:20

1500 руб./в час

20 мая 2023, в 13:21

1500 руб./за проект

Минуточку внимания

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    The <iframe> tag specifies an inline frame. It allows us to load a separate HTML file into an existing document.

    Code snippet:

    function getIframeContent(frameId) {
        var frameObj = 
            document.getElementById(frameId);
    
        var frameContent = frameObj.
            contentWindow.document.body.innerHTML;
            
        alert("frame content : " + frameContent);
    }
    

    Some of the definitions are given below:

    • getIframeContent(frameId): It is used to get the object reference of an iframe.
    • contentWindow: It is a property which returns the window object of the iframe.
    • contentWindow.document: It returns the document object of iframe window.
    • contentWindow.document.body.innerHTML: It returns the HTML content of iframe body.

    Example: The following example demonstrates to include separate HTML file into existing document.

    <!DOCTYPE html>

    <html>

    <head>

        <title>

            How to get HTML content of 

            an iFrame using javascript?

        </title>

    </head>

    <body>

        <iframe id="frameID" src=

            "ContentOfFrame.html">

        </iframe>

        <a href="#" onclick=

            "getIframeContent('frameID');">

            Get the content of Iframe

        </a>

        <script>

            function getIframeContent(frameID) {

                var frameObj = 

                    document.getElementById(frameID);

                var frameContent = frameObj

                    .contentWindow.document.body.innerHTML;

                alert("frame content : " + frameContent);

            }

        </script>

    </body>

    </html>

    ContentOfFrame.html The following example demonstrates the HTML code content of file “ContentOfFrame.html”

    <!DOCTYPE html>

    <html>

    <body>

        GeeksForGeeks: A Computer 

        Science Portal For Geeks

        (It is loaded inside the 

        iframe)

    </body>

    </html>

    Output:

    Last Updated :
    05 Jun, 2020

    Like Article

    Save Article

    Добавить комментарий