In HTML5, is the localStorage object isolated per page/domain?
It's per domain and port (the same segregation rules as the same origin policy), to make it per-page you'd have to use a key based on the location
, or some other approach.
You don't need a prefix, use one if you need it though. Also, yes, you can name them whatever you want.
Per-page localStorage?
As stated here, localStorage is scoped by protocol, domain and port, nothing else.
And with this, even by prefixing each localStorage key by a unique page token (i.e. localStorage.set('page1.' + key)
), it wouldn't avoid another page from getting those info, so no simple way to avoid information leak.
LocalStorage per page rather than (sub)domain?
I have a function that generates a key for me, based on the page name (gotten from window.location) and appended with what the key would have been, then I store the data in localstorage.
function findPageName() {
var path = window.location.pathname,
s = path.split('/'),
l = s.length,
k = path.length,
aux = 0;
if (s[l - 1]) {
return s[l - 1];
} else if (l) { // l will always be a min of 2 (try '/'.split('/') )
return s[l - 2];
} else if (k == 0) {
return '/'; //you likely want to replace this with another value
} else {
return s[1];
}
}
function getKey(key) {
return getPageName() + key;
}
Does localStorage.clear() will clear items stored by other sites also?
The LocalStorage
is based on the domain. So when you have the local storage cleared, it will be cleared for that domain. If you are using file:///
protocol (opening files) then everything is cleared.
From the spec:
The
localStorage
object provides a Storage object for an origin.User agents must have a set of local storage areas, one for each origin.
An origin is a single domain. This means, www.example.com
has it's own and example.com
has it's own.
Related: In HTML5, is the localStorage object isolated per page/domain?
Related Topics
JavaScript Does Not Fire After Appending
How to Move an Element into Another Element
How to Change an Element'S Text Without Changing Its Child Elements
Where to Place JavaScript in an HTML File
Onclick to Get the Id of the Clicked Button
Load and Execution Sequence of a Web Page
Using an HTML Button to Call a JavaScript Function
Set the Value of an Input Field
"Submit Is Not a Function" Error in JavaScript
Changing Website Favicon Dynamically
Rendering HTML Inside Textarea
Show/Hide 'Div' Using JavaScript
How to Get Value of Selected Radio Button
How to Show the "Are You Sure You Want to Navigate Away from This Page" When Changes Committed
Custom Attributes - Yea or Nay
Angularjs - Value Attribute on an Input Text Box Is Ignored When There Is a Ng-Model Used