Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change iframe src without reloading the iframe?

I have two frames of which I copy the content of the first (myframe) to the second (myframe2) using JavaScript and set myframe2's src:

<iframe id="myframe" src="../Page1.aspx" width="100%" height="100px"></iframe>
<iframe id="myframe2"  width="100%" height="100px"></iframe>

<button onclick="myFunction();return false;">Try it</button>

<script>
    function myFunction() {
        var iframe1 = document.getElementById("myframe");
        var iframe2 = document.getElementById("myframe2");

        iframe2.contentWindow.document.body.parentElement.innerHTML = iframe1.contentWindow.document.body.parentElement.innerHTML;
        iframe2.setAttribute("src", iframe1.src);
    }
</script>

FrameSecond reloads after "src" attribute is set, but I don't need it to do so. Can anyone help me with this?

like image 280
Aliasghar Bahrami Avatar asked Jul 16 '16 07:07

Aliasghar Bahrami


2 Answers

Use replaceState(state, title, URL):

iframe2.contentWindow.history.replaceState('WhatEverNameYouWant', "", iframe1.src);
like image 123
smac89 Avatar answered Sep 23 '22 01:09

smac89


I had much the same problem. I needed to "know" what the location of the document loaded into my Iframe was, so I could show its location somewhere else. I had inputs which changed the location of the iframe by setting

myIFrame.src =  ... 

This worked fine except then I realized when I clicked back- or forward -button the content of the IFrame changed, yet that did not (seem to) change the value of the src-attribute of the referring IFrame element. Same problem when I added links into the iframe documents to navigate between them.

My solutions was to in the onload-handler of the document loaded into the IFrame record the loaded URL into a field of the parent window. When the containing document needs to know what is loaded in the IFrame it consults that variable rather than rely on the .src -attribute of its IFrame -element, which seems to not be up-to-date with the actual contents of the iframe automatically.

BTW. I also tried explicitly setting the value of the .src -attribute of the iframe elemen from the onload -handler of the iframed document. That worked yes but caused a visible second load of the iframe contents. By using a separate explicit location to store the url of the document loaded into the iframe it does not get loaded twice, and everything works smoothly.

like image 43
Panu Logic Avatar answered Sep 25 '22 01:09

Panu Logic