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

荒凉一梦 提交于 2019-12-02 00:32:47

问题


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!


回答1:


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);
};


来源:https://stackoverflow.com/questions/29859048/updating-an-iframe-history-and-url-then-making-it-work-with-back-button

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