问题
I want to capture at maximum the last 3 pages visited, and store the url and other string data such as title and description.
local storage seems the best bet, but what method should I use to save the data?
If I create an array i saw on SO how to push that as an object
var testObject = { 'url': window.location.href, 'location': 'Japan', 'desc': 'some brief description text' };
localStorage.setItem('testObject', JSON.stringify(testObject));
but how could I store/update (in this example) the most recent 3 of these arrays in localStorage, and then retrieve all 3 in order of last visited to be listed out on a page?
回答1:
You could take advantage of the built-in shift
and push
methods:
shift
: it removes the last element from an arraypush
: it adds one or more elements to the end of an array
The first time a page is requested, save your object in an array and place it in your localStorage
:
var items = [{ 'url': window.location.href, 'location': 'Japan', 'desc': 'some brief description text' }];
localStorage.setItem('testObject', JSON.stringify(items));
On ongoing call, test the length
of the array and shift
or push
your new item accordingly:
var items = JSON.parse(localStorage.getItem('testObject'));
if(items.length === 3) {
items.shift(); //the first item in the array is removed. So length is 2
}
items.push(your new item); //length is 3
Finally save your new items into the storage:
localStorage.setItem('testObject', JSON.stringify(items));
You could create a find
method to look for what you need to work with:
var find = function(arr, url) {
return arr.filter(function(el) {
return el.url === url;
})[0];
}
var item = find(items, 'http://url.com');
Note that localStorage
is part of ECMAScript 5th edition. So provide a polyfill for browsers that don't support it. If cross-browser compatibility is required ensure that both shift and push are present (though pretty standard methods).
See Mozilla MDN for more information about Array:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
来源:https://stackoverflow.com/questions/21779476/use-localstorage-to-display-the-last-n-pages-visited