Cross Domain Local Storage
- Problem
- Solution
- Why not use cookies?
- Installation
- Usage
- API
- Angular Support
- Demo
- Tests
- Limitations
Problem
As for now, standard HTML5 Web Storage (a.k.a Local Storage) doesn't now allow cross domain data sharing.
This may be a big problem in an organization which have a lot of sub domains and wants to share client data between them.
Solution
xdLocalStorage is a lightweight js library which implements LocalStorage interface and support cross domain storage by using iframe post message communication.
Why not use cookies?
Although cookies can be shared between sub domains, cookies have the overhead of being sent to the server on each request.
They're also have a size limit (4K for all cookies together)
Installation
Download latest release from here or use bower/npm (recommended)
bower install xdLocalStorage --save
or
npm install --save xdlocalstorage
Usage
- Create an empty html with the following content:
<!DOCTYPE html>
<html>
<head>
<script src="xdLocalStoragePostMessageApi.min.js"></script>
</head>
<body>
This is the magical iframe
</body>
</html>
- On your client page (the page you will read/store your data from) add:
<script src="scripts/xdLocalStorage.min.js"></script>
xdLocalStorage.init(
{
iframeUrl:'path to your html from step 1',
initCallback: function () {
console.log('Got iframe ready');
}
}
);
API
xdLocalStorage.setItem(key, value, function (data) { });
xdLocalStorage.getItem(key, function (data) { });
xdLocalStorage.removeItem(key, function (data) { });
xdLocalStorage.key(index, function (data) { });
xdLocalStorage.clear(function (data) { });
Angular Support
UPDATE: Since version 2.0.0 the xdLocalStorage service supoprts promise interface hence no more annoying callbacks :)
angular.module('yourModule', ['xdLocalStorage']).run(function (xdLocalStorage) {
xdLocalStorage.init(
{
iframeUrl:'path to your html from step 1'
}).then(function () {
console.log('Got iframe ready');
});
});
- inject xdLocalStorage where ever you want and use the API
angular.module('yourModule').run(function(xdLocalStorage) {
xdLocalStorage.getItem(key).then(function (response) {
console.log(response.value);
});
});
Demo
Here's the demo
Tests
I covered the basic API with tests here
Limitations
Apple has updated the defaults on Safari 7+ both on desktop and mobile to block 3rd party data. The option is now called "Block cookies and other website data" which refers to things like localstorage which are now completely isolated by domain.
This implies that unfortunately this library will not be able to share cross domain information on Safari 7+.