1

Here's the code:

<!DOCTYPE html>
 <html>
  <head>
   <script>
 var URL = prompt("Insert URL here", "http://www.example.com"); //Asks user for URL
   </script>
  </head>
  <body>
   <iframe onload="this.src=URL" height="610px" width="1320" id="window"></iframe>
  </body>
</html>

I'm trying to make the file load a URL into <iframe>, but when it finishes loading the URL, it reloads because of the onload attribute. Is there another attribute I should use? Thanks in advance.

2 Answers 2

1

It's difficult to use an iframe on an online editor because of the sandbox environment but it'll behave normal under normal conditions. As a valid test, you can enter http://example.com it's whitelisted.

UPDATE

Added a PLUNKER since SO sandboxes iframes.

EDIT

I added another way to manipulate the iframe you might be interested in. Itonly involves HTML, no JS. Notice the anchor to example.com. Basically all you need to do is the following:

  1. Add a name attribute to the iframe (I always have id and name the same)
  2. On the anchor, you change the target attribute value to the value of the iframe's name value.

So in this demo the part inside {{{...}}} is the trick. The brackets are added for emphasis do not include them into the code to use.

<a href="http://example.com" {{{target="site"}}}>Example.com</a>

<iframe id="site" {{{name="site"}}} src="/" width="100%" height="100%" frameborder="0"></iframe>

function changeSrc(src) {
  var iframe = document.getElementById('site');
  iframe.src = src;
}
body {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}
section {
  height: 100%;
  width: 100%;
  overflow-y: auto;
}
<form id="form" onchange="changeSrc(url.value);">
  <fieldset>
    <legend>Enter URL</legend>
    <input id="url">


  </fieldset>
</form>
<a href="https://example.com" target="site">Example.com</a>
<section>
  <iframe id="site" name="site" src="/" width="100%" height="100%" frameborder="0"></iframe>
</section>

Sign up to request clarification or add additional context in comments.

2 Comments

What does the "/" value for source do?
It points to root in this example root is: stacksnippets.net I think.
1

try this

<!DOCTYPE html>
<html>
    <head>
        <script>
            var URL = prompt("Insert URL here", "http://www.example.com"); //Asks user for URL
            if(URL) document.getElementById('window').src = URL;
        </script>
    </head>
    <body>
            <iframe height="610px" width="1320" id="window">
    </body>
</html>

the onload attribute you had on your iframe is fired when the iframe loads (and not when the page window loads), hence it setting the src again and then reloading the page into an endless loop.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.