Search code examples
javascripthtmliframegetelementsbytagname

document.getElementsByTagName doesn't work inside an iframe?


I have a simple html document containing an iframe. In this iframe there is a wikipedia page. For now, I'm just trying to take the title of the wikipedia page and to output it into the log console. Here's the code I'm using :

<!DOCTYPE html>


<html>
    <head>  <!-- Tout ce qui est pas dans le contenu -->
        <title> example</title>
        
    </head>
    
    <body>

        <h1>A Web Page</h1>

        <script>
            const iframe = document.createElement("iframe");
            iframe.src = "https://en.wikipedia.org/wiki/Mathematics";
            iframe.height = 800;
            iframe.width = 900;
            document.body.appendChild(iframe);
            var elmnt = iframe.contentWindow.document.getElementsByTagName("H1");
            console.log("the title is " + elmnt[0]);

        </script>
          
    </body>
</html>

I expect to get "the title is Mathematics" in the console from this example, but instead I get, "the title is undefined". I checked and "Mathematics" is indeed inside a h1 tag on wikipedia, so I don't understand the issue here.


Solution

  • It's a timing issue.

    You aren't waiting for the document to load, so the HTML hasn't been parsed and the element doesn't exist yet.

    iframe.addEventListener("load", () => {
        var elmnt = iframe.contentWindow.document.getElementsByTagName("H1");
        console.log("the title is " + elmnt[0]);              
    })
    

    … solves that problem and you promptly run into the cross-origin security limits instead.