How do I load a URL specified in a textbox in an iframe?

心不动则不痛 提交于 2020-01-03 04:27:13

问题


I am creating a fake browser shell using CSS/HTML and Javascript (Netscape 4.0) and I would like to know if it is possible to load a URL typed in a text box in an iframe. I found something online and it loads pages in the same directory but not external URLs. here is that section of the code:

<input type="submit" name="submit" id="submit" value="Go" onclick='document.getElementById("theframe").src=document.getElementById("url").value; return false;' />

and here is the iframe code:

<iframe frameborder="0" class="iframe" id='theframe' style="width:100%; height:100%;" scrolling="yes"></iframe>

回答1:


At its most basic...

<script type="text/javascript">
function loadUrl() {
    document.getElementById("urlDisplay").src = document.getElementById("urlSource").value;
}
</script>

<p><input type="text" id="urlSource" value="http://www.cnn.com"> <input type="button" value="Go" onclick="loadUrl()">

<p><iframe id="urlDisplay" width="200" height="200">



回答2:


Before I answer your question, take note that some sites refuse to load the page inside an iframe (example: http://google.com) and some sites would force to load the page outside an iframe (example: http://www.tumblr.com). Yeah I know, it sucks.

Okay, so here's my take on solving your problem:

<form action="" method="post" id="url-setter">
    <input type="text" name="url" id="url" />
    <button type="submit" name="submit">Change URL</button>
</form>
<iframe id="the-frame" width="640" height="480" src=""></iframe>
<script type="text/javascript">
    (function () {
        "use strict";
        var url_setter = document.getElementById('url-setter'), url = document.getElementById('url'), the_iframe = document.getElementById('the-frame');
        url_setter.onsubmit = function (event) {
            event.preventDefault();
            the_iframe.src = url.value;
        };
    }());
</script>


来源:https://stackoverflow.com/questions/19393756/how-do-i-load-a-url-specified-in-a-textbox-in-an-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!