Fred the Man
Fred the Man

Reputation: 106

Create an iframe with only javascript

I have been struggling on one of those programing challenge sites for a while. It has a console type thing that lets me enter javascript and press a run button. I need to create an iframe inside of that webpage with another webpage inside of it (for example, im on thiswebsite.com/level1 and I need to create the iframe with thiswebsite.com/level2 inside of it).

Have tried creating iframes as follows:

document.getElementById('someDiv').innerHTML = '<iframe src="thissite.com/level2/" height= 300 width=400>';

However it does not run when I try this, is there an alternative way? Thanks.

Upvotes: 5

Views: 7635

Answers (2)

murli2308
murli2308

Reputation: 2994

Use createElement method of document

var a = document.createElement('iframe');
a.src = "your path will go here"; //add your iframe path here
a.width = "1000";
a.height = "500";
document.querySelector('body').appendChild(a)

I just append the iframe to body. To append it to someDiv replace last line with below code

document.getElementById('someDiv').appendChild(a);

Upvotes: 6

Xameer
Xameer

Reputation: 31237

I doubt that the site doesn't allow you to create iframes.

Like, if you try the below code in your Console

    //define function
    function prepareiFrame() {
        var ifrm = document.createElement("iframe");
        ifrm.setAttribute("src", "https://google.com/");
        ifrm.style.width = "640px";
        ifrm.style.height = "480px";
        document.body.appendChild(ifrm);
    }

    //call it
    prepareiFrame()

Stackoverflow will throw the below error:

Refused to display 'https://www.google.co.in/?gfe_rd=cr&ei=OoWPV7agCuHt8wf3v6egDA' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

Upvotes: 1

Related Questions