119

Take a look at this simple HTML:

<div id="wrap1">
  <iframe id="iframe1"></iframe>
</div>
<div id="warp2">
  <iframe id="iframe2"></iframe>
</div>

Let's say I wanted to move the wraps so that the #wrap2 would be before the #wrap1. The iframes are polluted by JavaScript. I am aware of jQuery's .insertAfter() and .insertBefore(). However, when I use those, the iFrame loses all of its HTML, and JavaScript variables and events.

Lets say the following was the iFrame's HTML:

<html>
  <head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
      // The variable below would change on click
      // This represents changes on variables after the code is loaded
      // These changes should remain after the iFrame is moved
      variableThatChanges = false;
      $(function(){
        $("body").click(function(){ 
          variableThatChanges = true; 
        });
      });
    </script>
  </head>
  <body>
    <div id='anything'>Illustrative Example</div>
  </body>
</html>

In the above code, the variable variableThatChanges would...change if the user clicked on the body. This variable, and the click event, should remain after the iFrame is moved (along with any other variables/events that have been started)

My question is the following: with JavaScript (with or without jQuery), how can I move the wrap nodes in the DOM (and their iframe childs) so that the iFrame's window stays the same, and the iFrame's events/variables/etc stay the same?

GSerg
  • 76,472
  • 17
  • 159
  • 346
JCOC611
  • 19,111
  • 14
  • 69
  • 90
  • Asked before (long time ago) -> http://stackoverflow.com/questions/2885504/how-to-move-iframe-along-the-dom-without-losing-its-content and http://stackoverflow.com/questions/3029871/move-iframe-in-the-dom-using-jquery – Manse Nov 29 '11 at 22:01
  • Current Bug raised with Mozilla ... https://bugzilla.mozilla.org/show_bug.cgi?id=254144 – Manse Nov 29 '11 at 22:04
  • @ManseUK: the other questions didn't really help...but the bug is pretty interesting. – JCOC611 Nov 29 '11 at 22:12
  • Is that same bug reported for the other browsers? Chrome for example exhibits the same behavior, and I wouldn't be surprised if that wasn't the case for most other browsers too. – Kevin B Nov 29 '11 at 22:16
  • One possible solution is to move the _other_ content around the iframe instead of moving the iframe. – Salman A Jun 07 '13 at 08:30
  • 1
    @SalmanA how do you move a parent "around" a child? – djechlin Oct 05 '16 at 21:33
  • What is the desired effect? would it be possible to swap the ID's of the parent elements? and then reload any javascript that references them? (possibly achieving the desired effect without moving the iframes) Another option might be to move them around by changing the css on the fly. – acolchagoff Oct 11 '16 at 15:34
  • 1
    @denodster the desired effect way back when I opened this question was to change the order of a list of elements, each with `inline-block` display...at this point, I'm guessing a generic solution (or effectively the statement that such is impossible) would be most appropriate, given the interest of others. – JCOC611 Oct 11 '16 at 15:55
  • look up adoptNode() – Muhammad Umer Mar 27 '21 at 18:25

10 Answers10

53

This answer is related to the bounty by @djechlin

A lot of search on the w3/dom specs and didn't find anything final that specifically says that iframe should be reloaded while moving in the DOM tree, however I did find lots of references and comments in the webkit's trac/bugzilla/microsoft regarding different behavior changes over the years.

I hope someone will find anything specific regarding this issue, but for now here are my findings:

  1. According to Ryosuke Niwa - "That's the expected behavior".
  2. There was a "magic iframe" (webkit, 2010), but it was removed in 2012.
  3. According to MS - "iframe resources are freed when removed from the DOM". When you appendChild(node) of existing node - that node is first removed from the dom.
    Interesting thing here - IE<=8 didn't reload the iframe - this behavior is (somewhat) new (since IE>=9).
  4. According to Hallvord R. M. Steen comment, this is a quote from the iframe specs

    When an iframe element is inserted into a document that has a browsing context, the user agent must create a new browsing context, set the element's nested browsing context to the newly-created browsing context, and then process the iframe attributes for the "first time".

    This is the most close thing I found in the specs, however it's still require some interpretation (since when we move the iframe element in the DOM we don't really do a full remove, even if the browsers uses the node.removeChild method).

Dekel
  • 60,707
  • 10
  • 101
  • 129
53

It isn't possible to move an iframe from one place in the dom to another without it reloading.

Here is an example to show that even using native JavaScript the iFrames still reload: http://jsfiddle.net/pZ23B/

var wrap1 = document.getElementById('wrap1');
var wrap2 = document.getElementById('wrap2');
setTimeout(function(){
    document.getElementsByTagName('body')[0].appendChild(wrap1);
},10000);
Wesley Smith
  • 19,401
  • 22
  • 85
  • 133
Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • 5
    Well, if the iFrames reload then it's not an option. – JCOC611 Nov 29 '11 at 22:10
  • 3
    Right, the example's purpose is to show that even using native JavaScript the iFrames still reload. – Kevin B Nov 29 '11 at 22:11
  • Well, actually, I really don't care if it reloads or not, since their locations are `about:blank`, but what I do care about is losing the contents inside the frame. – JCOC611 Nov 29 '11 at 22:15
  • 1
    if it reloads, that would cause it to lose the contents inside the iframe. I guess you could grab the contents inside the iframe prior to moving it using jquery `$("#iframeid").contents()` however that will not get stored javascript data, it would have to be sent to the parent page by the iframe.(or the parent page would have to grab it from the iframe) – Kevin B Nov 29 '11 at 22:17
  • @JCOC611 or you might have the iFrame page store it's state in local storage and reset itself after moving – Wesley Smith Oct 09 '16 at 09:25
  • hmmm, I wonder why this 5 year old answered question is on the open bounty list? ....weird – Wesley Smith Oct 09 '16 at 09:27
  • 1
    DelightedD0D, the bounty was opened by @djechlin - "I wonder if this is still true in 2016" to see if anything changed in the past 5 years regarding this issue. You can check the summary in my answer regarding the changes during these years. – Dekel Oct 09 '16 at 12:24
  • Nothing has really changed since then. The only way of having an iframe that moves around without reloading is still putting it at the body level and moving it around with absolute positioning, thus avoiding moving it around in the DOM completely. This of course is not easy to maintain and should be avoided. – Kevin B Oct 10 '16 at 15:02
  • @KevinB, Change positioning is not exactly moving in the DOM :) – Dekel Oct 10 '16 at 15:35
  • @Milad i don't think i made any such claim. – Kevin B Oct 10 '18 at 06:15
24

Whenever an iframe is appended and has a src attribute applied it fires a load action similarly to when creating an Image tag via JS. So when you remove and then append them they are completely new entities and they refresh. Its kind of how window.location = window.location will reload a page.

The only way I know to reposition iframes is via CSS. Here is an example I put together showing one way to handle this with flex-box: https://jsfiddle.net/3g73sz3k/15/

The basic idea is to create a flex-box wrapper and then define an specific order for the iframes using the order attribute on each iframe wrapper.

<style>
  .container{
    display: flex;
    flex-direction: column;
  }
</style>
<div class="container">
  <div id="wrap1" style="order: 0" class="iframe-wrapper">
    <iframe id="iframe1" src="https://google.com"></iframe>
  </div>
  <div id="warp2" style="order: 1" class="iframe-wrapper">
    <iframe id="iframe2" src="https://bing.com"></iframe>
  </div>
</div>

As you can see in the JS fiddle these order styles are inline to simplify the flip button so rotate the iframes.

I sourced the solution from this StackOverflow question: Swap DIV position with CSS only

Hope that helps.

Community
  • 1
  • 1
PaulSCoder
  • 593
  • 5
  • 19
7

If you have created the iFrame on the page and simply need to move it's position later try this approach:

Append the iFrame to the body and use a high z-index and top,left,width,height to put the iFrame where you want.

Even CSS zoom works on the body without reloading which is awesome!

I maintain two states for my "widget" and it is either injected in place in the DOM or to the body using this method.

This is useful when other content or libraries will squish or squash your iFrame.

BOOM!

mattdlockyer
  • 6,984
  • 4
  • 40
  • 44
6

Unfortunately, the parentNode property of an HTML DOM element is read-only. You can adjust the positions of the iframes, of course, but you can't change their location in the DOM and preserve their states.

See this jsfiddle I created that provides a good test bed. http://jsfiddle.net/RpHTj/1/

Click on the box to toggle the value. Click on the "move" to run the javascript.

Matt H
  • 6,422
  • 2
  • 28
  • 32
4

This question is pretty old... but I did find a way to move an iframe without it reloading. CSS only. I have multiple iframes with camera streams, I dont like when they reload when i swap them. So i used a combination of float, position:absolute, and some dummy blocks to move them around without reloading them and having the desired layout on demand (resizing and all).

moeiscool
  • 1,318
  • 11
  • 14
  • 1
    Sounds like the only viable option. You should post the full solution you came up with! At least some basic code to get others started. Thanks! – JCOC611 Jun 19 '16 at 15:21
1

At least in some circumstances a shadow dom with slotting might be an option.

<template>
  <style>div {outline:1px solid black; height:45px}</style>
  <div><slot name="a" /></div>
  <div><slot name="b" /></div>
</template>
<div id="shadowhost">
  <iframe src="data:text/html,<button onclick='this.innerText+=`!`'>!</button>"
  slot="a" height=40px ></iframe>
</div>
<button onclick="ifr.slot= (ifr.slot=='a') ? 'b' : 'a';">swap</button>
<script>
  document.querySelector('#shadowhost').attachShadow({mode: 'open'}).appendChild(
    document.querySelector('template').content
  );
  ifr=document.querySelector('iframe');
</script>
T S
  • 1,656
  • 18
  • 26
0

If you are using the iframe to access pages you control, you could create some javascript to allow your parent to communicate with the iframe via postMessage

From there, you could build login inside the iframe to record state changes, and before moving dom, request that as a json object.

Once moved, the iframe will reload, you can pass the state data into the iframe and the iframe listening can parse the data back into the previous state.

Drew Major
  • 501
  • 1
  • 3
  • 18
  • Granted, this is a lot of code, assumes you control all data that will be displayed in frame, and still technically doesnt "maintain the state when moving in DOM" – Drew Major Oct 12 '16 at 16:07
0

PaulSCoder has the right solution. Never manipulate the DOM for this purpose. The classic approach for this is to have a relative position and "flip" the positions in the click event. It's only not wise to put the click event on the body, because it bubbles from other elements too.

$("body").click(function () {
    var frame1Height = $(frame1).outerHeight(true);
    var frame2Height = $(frame2).outerHeight(true);
    var pos = $(frame1).css("top");
    if (pos === "0px") {
        $(frame1).css("top", frame2Height);
        $(frame2).css("top", -frame1Height);
    } else {
        $(frame1).css("top", 0);
        $(frame2).css("top", 0);
    }
});

If you only have content that is not cross-domain you could save and restore the HTML:

var htmlContent = $(frame).contents().find("html").children();
// do something
$(frame).contents().find("html").html(htmlContent);

The advantage of the first method is, that the frame keeps on doing what it was doing. With the second method, the frame gets reloaded and starts it's code again.

-1

In response to the bounty @djechlin placed on this question, I have forked the jsfiddle posted by @matt-h and have come to the conclusion that this is still not possible.

http://jsfiddle.net/gr3wo9u6/

//this does not work, the frames reload when appended back to the DOM
function swapFrames() {
    var w1 = document.getElementById('wrap1');
    var w2 = document.getElementById('wrap2');
    var f1 = w1.querySelector('iframe');
    var f2 = w2.querySelector('iframe');

    w1.removeChild(f1);
    w2.removeChild(f2);
    w1.appendChild(f2);
    w2.appendChild(f1);
    //f1.parentNode = w2;
    //f2.parentNode = w1;

    //alert(f1.parentNode.id);
}
acolchagoff
  • 1,926
  • 3
  • 18
  • 30