5

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.

2
  • What seems to be your issue? I copy and Pasted the Exact code into a jsfiddle (with a different source) and it worked jsfiddle.net/yah18c73/1 Commented Jul 20, 2016 at 14:00
  • The site simply would not run it, I assume it was looking for another solution, the answer provided below did compile and run. This is why I was stuck, because my code should have worked. Commented Jul 20, 2016 at 14:02

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to set the size to this? Also this answer does run, thanks.
Wc. edited the answer check. you can specify any property which is valid html attribute. I will suggest to add class name also
a.width and a.height seems to be doing that only
1

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'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.