Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating an iframe, history and URL. Then making it work with back button

I'm having problems getting URL to update when hitting the back button on the browser (I'm on testing on Firefox). After updating the "src" property of the iframe I use replaceState to update the history. If I hit the back button after this the iframe will go back to the previous page but the URL does not update to reflect this.

function updateURLBar(urlInfo) {
    var stateObj = { foo: "bar" };
    document.getElementById("iframeContent").src = urlInfo[1];
    window.history.replaceState(stateObj, "page 2", urlInfo[0]);
}

Am I going about this the wrong way or am I just missing something. Thanks for any help in advanced!

like image 771
Ray Avatar asked Apr 24 '15 23:04

Ray


1 Answers

You may find the popstate event interesting.

https://developer.mozilla.org/en-US/docs/Web/Events/popstate

First, I would change few lines of code that you have...

function updateURLBar(urlInfo) {
    //we can get this stateObj later...
    var stateObj = { 
        foo: "bar",
        url: urlInfo[1]
    };

    //document.getElementById("iframeContent").src = urlInfo[1];

    // see EDIT notes
    changeIframeSrc(document.getElementById("ifameContent"), urlInfo[1]);

    //window.history.replaceState(stateObj, "page 2", urlInfo[0]);
    window.history.pushState(stateObj, "Page 2", urlInfo[0]);
}

And then you can add:

window.onpopstate = function(event) {
    //Remember our state object?
    changeIframeSrc( document.getElementById("iframeContent") ),event.state.url); // see EDIT notes.
};

EDIT

The Iframe caveat

There is a problem with using pushState and changing iframe src attributes. If an iframe is in the DOM, and you change the src attribute, this will add a state to the browsers history stack. Therefore, if you use history.pushState with iframe.src = url, then you will create 2 history entries.

The Workaround

Changing the src attribute of an iframe element when the iframe is not in the DOM will not push to the browsers history stack.

Therefore you could build a new iframe, set it's src attribute, and then replace the old iframe with the new one.

var changeIframeSrc = function(iframe, src) {
    var frame = iframe.cloneNode();
    frame.src = src;
    iframe.parentNode.replaceChild(frame, iframe);
};
like image 87
Norman Breau Avatar answered Oct 04 '22 14:10

Norman Breau