0

For a new web app I would like to modify history when users click on a link, so that the URL changes, but the page does not reload. I'll have some part of the page load in ajax. This can be done easily and is documented in a lot of places (e.g. Mozilla, diveintohtml5, Stack Overflow).

However, I'm wondering if there's a way to let the user modify the URL without reloading the page. Say for example someone gives them a link within the same domain, or they want to manually type the URL for some reason. I'd like to load the new page in the same way as I would if they had clicked a link - without reloading the page but rather modifying the history.

Is there any way to do this? Here's the gist of what I was thinking, but the magic functions getNewURLFromEvent, preventUserFromActuallyLeavingPage, and carryOn need to be implemented (if possible):

window.addEventListener('unload', function(event) {
    var newURL = getNewURLFromEvent(event);

    if (isInThisDomain(newURL)) {
        preventUserFromActuallyLeavingPage();
        window.history.pushState('content', 'title', document.URL);
    } else {
        // Let the user leave (the internet is a free place after all)
        carryOn();
    } 
});

function isInThisDomain(URL) {
    /* Would probably implement some error checking here too */
    var thisDomain = document.URL.match(/:\/\/(.+?)\//)[1],
        thatDomain = URL.match(/:\/\/(.+?)\//)[1]);

    return thisDomain === thatDomain;
}

function getNewURLFromEvent(e) {
    /* Figure out where the user want's to go */
}

function preventUserFromActuallyLeavingPage() {
    /* Since we're changing the content it still looks
        like the user's leaving, but really they haven't
        gone anywhere from the site's perspective */
}

function carryOn() {
    /* Essentially do nothing, but maybe more magic is needed? */
}

If you feel this is a bad idea - yet still possible - please explain why it's a bad idea.

Thank you.

4

1 回答 1

0

地址栏的值的任何更改,除了使用 URL 哈希,都会指示浏览器转到该位置。你不能(也不应该)改变这种行为。这将打开一大堆关于 URL 伪装和其他恶意软件的蠕虫。

于 2013-03-19T21:43:49.167 回答