Install iframe innerHTML without loading the page in it (with jquery)

I want to set the contents of the iframe dynamically when the pages in the iframe were not previously loaded.

I'm doing it:

iframe = $('<iframe id="thepage"></iframe>'); iframeHtml = 'iframeHtml'; $('body').append(iframe); iframe .contents() .html(iframeHtml); 

But it does not work, html is still empty.

+6
source share
5 answers

the best way to populate the contents of a frame is document.write

 var dstFrame = document.getElementById('yourFrameId'); var dstDoc = dstFrame.contentDocument || dstFrame.contentWindow.document; dstDoc.write(yourHTML); dstDoc.close() 

UPD:

 var iFrame = $('<iframe id="thepage"></iframe>'); $('body').append(iFrame); var iFrameDoc = iFrame[0].contentDocument || iFrame[0].contentWindow.document; iFrameDoc.write('<p>Some useful html</p>'); iFrameDoc.close(); 
+20
source

If you want to avoid using document.write , which is usually not recommended anymore, you can get the contents of the frame to add content:

 iframe = $('<iframe id="thepage"></iframe>') iframeHtml = 'iframeHtml' $('body').append(iframe) iframe.contents().find('body').html(iframeHtml) 
+8
source

Using jQuery, you can edit the iframe srcdoc attribute by passing it HTML as a string:

 $('#iframe_id').attr("srcdoc", htmlString); 
+5
source
 iframe = $('<iframe id="thepage"></iframe>'); iframeHtml = 'iframeHtml'; $('body').append(iframe); iframe .contents() .html(iframeHtml); 

the reason it doesn't work is because contents() returns a document object, and html() only works with HTMLElemnt objects, html() is basically a wrapper with an innerHTML attribute and document does not have such a property.

+3
source

var EditFrame = $ ("# EditWindow"). contents (). find ('body'); var message = "Your message to be displayed in the Iframe"; EditFrame.html (message); Your message which needs to show in Iframe

0
source

Source: https://habr.com/ru/post/1382475/


All Articles