Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iframe onload event when content is set from srcdoc

How can i specify an onload property for an iframe loaded from srcdoc attribute. For example:

<iframe id="Content" runat="server" srcdoc="Large HTML contents that are set from the server"></iframe>

I'm using asp.net webforms to populate the content from another server.

However, the normal way to trigger onload for an iframe would be the following, but that won't work:


$(function () {

    var iframe = document.getElementById(DocumentViewer.GetFrameClientID());

    console.log({iframe}) // OK

    iframe.onload = function () { // Never Trigger unless i add a src attribute instead of srcdoc
        console.log('loaded')
    }
})

I found an issue reported on github in 2018 "load" event handler is called prematurely for iframe.srcdoc

Any clue?

like image 786
Ali Kleit Avatar asked May 03 '26 08:05

Ali Kleit


1 Answers

A workaround that works for me (tested in current versions of Firefox and Chrome) is to set the srcdoc after having added the load listener, i.e. something like this:

<iframe title="..."></iframe>
const iframe = document.querySelector(`iframe`)

iframe.addEventListener(
    `load`,
    () => doSomethingWith(iframe.contentDocument),
)

iframe.srcdoc = `<p>The HTML code</p>`
like image 115
Peppe L-G Avatar answered May 05 '26 22:05

Peppe L-G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!