Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to push current page to the browser history

I have a page that user can use an input to filter result. After entering some characters into the input entry, instead of deleting it manually, people like to use back button in browser to return to the "empty" state of the input.

But the result is fetched by AJAX, which means the back button behavior is wrong(can't clear input entry, but just return to a previous page), is it possible to push an empty or current url into the back stack so that user can get the result as them desired?

To be clear, I want:

1) user enter some characters to the input entry
2) user press "filter" button
3) user press back button
4) the input entry is cleared
like image 939
Bin Chen Avatar asked Nov 06 '22 05:11

Bin Chen


1 Answers

Here are two general approaches to managing history. Both of them will work with the 'blank page' idea, although you may have to tweak the code.

The two ways of doing this use the fragment identifier or the new history API.

Using the fragment identifier would look something like this:

<body onhashchange="hashChanged()" onload="hashChanged()">

<input id='query'></input><button onclick="location.hash = '#'+document.getElementById('query').value">Query</button>

<script type="text/javascript">

function query(str) {
    // do your ajaxy thing
}

function hashChanged() {
    var str = location.hash.substring(1);
    document.getElementById('query').value = str;
    query(str);
}

</script>
</body>

This technique works on ie8, firefox 3.6 and chrome 5. You can hack similar things into earlier browsers by having hidden scroll areas and detecting scrolls, or by regularly polling the hash part of the location.

Another method uses the new history API

<body onload="queryChanged();">

<input id='query'></input><button onclick="history.pushState(str, "", "?query="+str);query(document.getElementById('query').value)">Query</button>

<script type="text/javascript">

function query(str) {
    // do your ajaxy thing
}

function queryChanged() {
    var str = "";
    var re = /[\?|&]query=([^&]*)/
    if (re.test(location.search)) {
        str = re.exec(location.search)[1];
    }
    document.getElementById('query').value = str;
    query(str);
}

window.onpopstate = queryChanged;
</script>
</body>

This works in recent firefox and chrome, but only ie10.

Of course, you would probably be best using a library. One old one is Really Simple History, but there are more modern plugins for jquery that provide similar features, e.g. BBQ or the hashchange plugin.

like image 192
kybernetikos Avatar answered Nov 09 '22 11:11

kybernetikos