How to replace iframe using the JavaScript

The task replace content of iframe after click on button inside Iframe.

It doesn’t easy task because we can’t change «src» attribute. It will be security issue if child iframe refers to other domain.

In common case for resolve this issue you should to delete old iframe from parent document and create new iframe. But for this you should have access to parent page.

Let’s have look at an example:

index.html (parent page contains iFrame)

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var NewIFrame = function() {
function remove(name){
var div = window.parent.document.getElementById(name);
if (typeof div != "undefined" || div != null) {
div.parentNode.removeChild(div);
}
}
newUrl = "child_two.html";
var my_frame = window.parent.document.getElementById('test_frame');
var widget;
if (typeof my_frame != "undefined" || my_frame != null) {
widget = my_frame.parentNode;
}
remove('test_frame');
var iframe = window.parent.document.createElement('iframe');
iframe.frameBorder='0';
iframe.scrolling='no';
iframe.id="test_frame";
iframe.setAttribute("class", 'my-style');
iframe.setAttribute("src", newUrl);
widget.appendChild(iframe);
}
</script>
<title>Home page</title>
</head>
<body>
<div id="container">
<iframe id="test_frame" src="child_one.html" width="468" height="200" align="left" scrolling="auto" frameborder="1">
</iframe>
</div>
</body>
</html>

child_one.html

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function NewIFrame() {
parent.NewIFrame();
}
</script>
<meta charset="utf-8">
<title>Child page 1</title>
</head>
<body>
<div id="content" width="400" height="150" style="background: #ccc;">
<a onclick="NewIFrame();" href="javascript:void(0)">Replace iFrame</a>
</div>
</body>
</html>

child_two.html

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
</script>
<meta charset="utf-8">
<title>Child page 2</title>
</head>
<body>
<div id="content" width="400" height="150" style="background: #fc0;">
Some information
</div>
</body>
</html>

Using this example you can replace iframe linked on other domain.

In Additional:

I also noticed that iframe difficult to hide. For exsample if you add style visibility: hidden; Internet Explorer may stop responding.
Style display: none; can cause problems with a page layout.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.