1

I want to call a function when a button within an iframe is clicked, but I am already having problems accessing the iframe document.

First, I followed this video, but null is returned when the function is called. The iFrame's content is hosted on the same server, using a wordpress installation in a folder (mydomain.com/fragen). The main page is mydomain.com, so that should not be the issue, right? Here is the code I was using. Printing a string to the console works.

<button onclick="test()">Test</button>

<iframe id="myIframe" src="mydomain.com/fragen/wp-admin/admin-ajax.php?action=h5p_embed&id=24" width="100%" height="525" frameborder="0" allowfullscreen="allowfullscreen" title="Diagnosetext">
</iframe>

<script>
const myIframe = document.querySelector("#myIframe");

function test() {
    const iframeWindow = myIframe.contentWindow;
    console.log(iframeWindow);
}
</script>
  • Your code looks fine and CORS should not be an issue in your case.The `contentWindow` property may be `null` if the iframe's contents have not yet been added to the DOM of the iframe. Have you tried to wait for the iframe's `load` event to fire before accessing the `contentWindow`? – Oliver Tacke Apr 23 '22 at 18:56
  • Thanks for your answer! I tried this `

    ` example, but it still cannot access the document. The iFrame seems to be like a black box.
    – Olivander12 May 07 '22 at 07:19
  • You will have to add the listener to the iframe before setting the `src` attribute, so you will need to create the iframe programmatically as well. – Oliver Tacke May 07 '22 at 11:03

0 Answers0