Iframe Is Not Working. Struggling to Execute Script Tags in Iframe

I am working with iframe tag for displaying ads.

I am using below code for it -

<iframe id="iframe"></iframe>

JS -

var iframe = document.getElementById('abc');

var doc = iframe.contentDocument ? iframe.contentDocument :(iframe.contentWindow ? iframe.contentWindow.document : iframe.document)

doc.open();

doc.write('<scr'+'ipt src=""></scr' + 'ipt>');

doc.close();

I tried it on normal HTML page and body gets blank in inner document of Iframe, but same code I execute in codepen it get executed, and body filled with executed script.

I needed solution or alternate solution to make it work.

1 Answer

Try oldskool

DEMO

<iframe name="iframe" src="emptypage.html"></iframe>

JS -

window.onload=function() {   
  var iframe = window.frames['iframe'];
  var doc = iframe.document;
  doc.write('<scr'+'ipt src=""></scr' + 'ipt>');
  doc.close();
}

Here is what I see now I add the script to another iframe raw and turn off ad blocking so it seems to work.

23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest