Coder Social home page Coder Social logo

cross-storage's Introduction

cross-storage

Cross domain local storage, with permissions. Enables multiple browser windows/tabs, across a variety of domains, to share a single localStorage. Features an API using ES6 promises.

Build Status

Overview

The library is a convenient alternative to sharing a root domain cookie. Unlike cookies, your client-side data isn't limited to a few kilobytes - you get up to 2.49M chars. For a client-heavy application, you can potentially shave a few KB off your request headers by avoiding cookies. This is all thanks to LocalStorage, which is available in IE 8+, FF 3.5+, Chrome 4+, as well as a majority of mobile browsers. For a list of compatible browsers, refer to caniuse.

How does it work? The library is divided into two types of components: hubs and clients. The hubs reside on a host of choice and interact directly with the LocalStorage API. The clients then load said hub over an embedded iframe and post messages, requesting data to be stored, retrieved, and deleted. This allows multiple clients to access and share the data located in a single store.

Care should be made to limit the origins of the bidirectional communication. As such, when initializing the hub, an array of permissions objects is passed. Any messages from clients whose origin does not match the pattern are ignored, as well as those not within the allowed set of methods. The set of permissions are enforced thanks to the same-origin policy. However, keep in mind that any user has full control of their local storage data - it's still client data. This only restricts access on a per-domain or web app level.

Hub

// Config s.t. subdomains can get, but only the root domain can set and del
CrossStorageHub.init([
  {origin: /\.example.com$/,            allow: ['get']},
  {origin: /:\/\/(www\.)?example.com$/, allow: ['get', 'set', 'del']}
]);

Note the $ for matching the end of the string. The RegExps in the above example will match origins such as valid.example.com, but not invalid.example.com.malicious.com.

Client

var storage = new CrossStorageClient('https://store.example.com/hub.html');

storage.onConnect().then(function() {
  return storage.set('newKey', 'foobar');
}).then(function() {
  return storage.get('existingKey', 'newKey');
}).then(function(res) {
  console.log(res.length); // 2
}).catch(function(err) {
  // Handle error
});

Installation

The library can be installed via bower:

bower install cross-storage

Or using npm:

npm install cross-storage

along with browserify:

var CrossStorageClient = require('cross-storage').CrossStorageClient;
var CrossStorageHub    = require('cross-storage').CrossStorageHub;

When serving the hub, you may want to set the CORS and CSP headers for your server depending on client/hub location. For example:

{
  'Access-Control-Allow-Origin':  '*',
  'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE',
  'Access-Control-Allow-Headers': 'X-Requested-With',
  'Content-Security-Policy':      "default-src 'unsafe-inline' *",
  'X-Content-Security-Policy':    "default-src 'unsafe-inline' *",
  'X-WebKit-CSP':                 "default-src 'unsafe-inline' *",
}

If using inline JS to create the hub, you'll need to specify unsafe-inline for the CSP headers. Otherwise, it can be left out if simply including the init code via another resource.

API

CrossStorageHub.init(permissions)

Accepts an array of objects with two keys: origin and allow. The value of origin is expected to be a RegExp, and allow, an array of strings. The cross storage hub is then initialized to accept requests from any of the matching origins, allowing access to the associated lists of methods. Methods may include any of: get, set, del, getKeys and clear. A 'ready' message is sent to the parent window once complete.

CrossStorageHub.init([
  {origin: /localhost:3000$/, allow: ['get', 'set', 'del', 'getKeys', 'clear']}
]);

new CrossStorageClient(url, [opts])

Constructs a new cross storage client given the url to a hub. By default, an iframe is created within the document body that points to the url. It also accepts an options object, which may include a timeout, frameId, and promise. The timeout, in milliseconds, is applied to each request and defaults to 5000ms. The options object may also include a frameId, identifying an existing frame on which to install its listeners. If the promise key is supplied the constructor for a Promise, that Promise library will be used instead of the default window.Promise.

var storage = new CrossStorageClient('http://localhost:3000/hub.html');

var storage = new CrossStorageClient('http://localhost:3000/hub.html', {
  timeout: 5000,
  frameId: 'storageFrame'
});

CrossStorageClient.prototype.onConnect()

Returns a promise that is fulfilled when a connection has been established with the cross storage hub. Its use is required to avoid sending any requests prior to initialization being complete.

storage.onConnect().then(function() {
  // ready!
});

CrossStorageClient.prototype.set(key, value)

Sets a key to the specified value. Returns a promise that is fulfilled on success, or rejected if any errors setting the key occurred, or the request timed out.

storage.onConnect().then(function() {
  return storage.set('key', JSON.stringify({foo: 'bar'}));
});

CrossStorageClient.prototype.get(key1, [key2], [...])

Accepts one or more keys for which to retrieve their values. Returns a promise that is settled on hub response or timeout. On success, it is fulfilled with the value of the key if only passed a single argument. Otherwise it's resolved with an array of values. On failure, it is rejected with the corresponding error message.

storage.onConnect().then(function() {
  return storage.get('key1');
}).then(function(res) {
  return storage.get('key1', 'key2', 'key3');
}).then(function(res) {
  // ...
});

CrossStorageClient.prototype.del(key1, [key2], [...])

Accepts one or more keys for deletion. Returns a promise that is settled on hub response or timeout.

storage.onConnect().then(function() {
  return storage.del('key1', 'key2');
});

CrossStorageClient.prototype.getKeys()

Returns a promise that, when resolved, passes an array of keys currently in storage.

storage.onConnect().then(function() {
  return storage.getKeys();
}).then(function(keys) {
  // ['key1', 'key2', ...]
});

CrossStorageClient.prototype.clear()

Returns a promise that, when resolved, indicates that all localStorage data has been cleared.

storage.onConnect().then(function() {
  return storage.clear();
});

CrossStorageClient.prototype.close()

Deletes the iframe and sets the connected state to false. The client can no longer be used after being invoked.

storage.onConnect().then(function() {
  return storage.set('key1', 'key2');
}).catch(function(err) {
  // Handle error
}).then(function() {
  storage.close();
});

Compatibility

For compatibility with older browsers, simply load a Promise polyfill such as es6-promise.

You can also use RSVP or any other ES6 compliant promise library. Supports IE8 and up using the above polyfill. A JSON polyfill is also required for IE8 in Compatibility View. Also note that catch is a reserved word in IE8, and so error handling with promises can be done as:

storage.onConnect().then(function() {
  return storage.get('key1');
}).then(function(res) {
  // ... on success
})['catch'](function(err) {
  // ... on error
});

Breaking Changes

API breaking changes were introduced in both 0.6 and 1.0. Refer to releases for details.

Notes on Safari 7+ (OSX, iOS)

All cross-domain local storage access is disabled by default with Safari 7+. This is a result of the "Block cookies and other website data" privacy setting being set to "From third parties and advertisers". Any cross-storage client code will not crash, however, it will only have access to a sandboxed, isolated local storage instance. As such, none of the data previously set by other origins will be accessible. If an option, one could fall back to using root cookies for those user agents, or requesting the data from a server-side store.

Compression

Most localStorage-compatible browsers offer at least ~5Mb of storage. But keys and values are defined as DOMStrings, which are UTF-8 encoded using single 16-bit sequences. That means a string of ~2.5 million ASCII characters will use up ~5Mb, since they're 2 bytes per char.

If you need to maximize your storage space, consider using lz-string. For smaller strings, it's not uncommon to see a 50% reduction in size when compressed, which will bring you a lot closer to 5 million characters. At that point, you're only limited by the average compression rate of your strings.

Building

The minified, production JavaScript can be generated with gulp by running gulp dist. If not already on your system, gulp can be installed using npm install -g gulp

Tests

Tests can be ran locally using npm test. Tests are ran using Zuul, and the Travis CI build uses Sauce Labs for multi-browser testing as well.

Copyright and license

Copyright 2016 Zendesk

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

cross-storage's People

Contributors

bolshchikov avatar danielstjules avatar migg24 avatar pixeldrew avatar tehdb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cross-storage's Issues

the set item return state null

i am trying to redirect my logined user to my sub domain with his credentials so i search about cross local storage and i found this library cross-storage and found this example in angular but when i am trying to set key and then console get that key it return with this

ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}
__zone_symbol__state: null
__zone_symbol__value: []}

here what i done in my component

storage: any;
crossDomainItem:any
constructor(private dialog: MatDialog, public authService: AuthService, private router: Router) {
   CrossStorageHub.init([
 {origin: /localhost:4200$/, allow: ['get', 'set', 'del', 'getKeys', 'clear']},
 {origin: /localhost:5000$/, allow: ['get', 'set', 'del', 'getKeys', 'clear']}
]);
this.storage = new CrossStorageClient('http://localhost:4200/home', {
 timeout: 30000000, frameId: 'storageFrame'
});

}

ngOnInit(): void {


this.storage.onConnect().then(() => {
 this.storage.set('cross-domain-item', 'First application cross domain item');
 this.storage.set('lol', 'lol');
});
this.crossDomainItem = this.storage.onConnect().then(() => {
 console.log(this.storage.get('cross-domain-item'));
 console.log(this.storage.get('lol'));
 return this.storage.get('cross-domain-item');
});
}

and loaded the library in angular.json like this

"scripts": [
        "./node_modules/cross-storage/lib/hub.js",
        "./node_modules/cross-storage/lib/client.js"
      ]

Error handling onConnect()

Hi,

First of all thanks for this really useful library. It should solve the problem I've been trying to solve for days, if only I can get it to work!

I'm new to promises and perhaps I'm missing something. I can't seem to gets a successful connection to the hub and can't tell why since there's no connection error callback. Is there a way to handle connection errors to the hub using promises?

In the example code below the catch never gets called because it can't connect for some reason.

var storage = new CrossStorageClient('https://store.example.com/hub.html');

storage.onConnect().then(function() {
// Set a key with a TTL of 90 seconds
return storage.set('newKey', 'foobar', 90000);
}).then(function() {
return storage.get('existingKey', 'newKey');
}).then(function(res) {
console.log(res.length); // 2
}).catch(function(err) {
// Handle error
});

Any guidance would be extremely appreciated.

Thank you.

document is not defined

when i use React server and renderToString then the error occured while webpack recompiling my code, it work just fine before i import cross-storage and use onConnect
error

please help, thanks :)

Error: CrossStorageClient could not connect at client.js:152

Hello I am getting an error "Error: CrossStorageClient could not connect at client.js:152". I have two sub domains auth-example.com and expert-example.com. I am declaring hub in auth-example.com like this.
"CrossStorageHub.init([{origin: /://(www.)?auth-example.com$/, allow: ['get', 'set', 'del']}]);"
and client side is expert-example.com
" var storage = new CrossStorageClient('https://auth.example.com');",
everything works perfect only on localhosts but error is occurring on live. and I can console in auth-example.com(in hub) but getting error on sub domains side (client side) Anyone can help me?

nexus 4, android 5.1 , Chrome 43

Error: CrossStorageClient could not connect at eval (.../node_modules/cross-storage/lib/client.js:151:14)

Only happens on my nexus 4. Is there a known issue or maybe I'm just missing something?

Cross-storage does not work in an Excel add-in

I have been using cross-storage for a while for an Excel add-in. It works for almost all the tasks except one odd problem. To reproduce the problem:

  • Sign in with third-party authentication such as Google. A dialog is opened by Office.context.ui.displayDialogAsync. The sign-in works and the dialog is closed.
  • Then I try to sign out, which cannot work, and I can see the following message in console.
    Screenshot 2023-04-02 at 19 11 32
  • If I reload the add-in, I can still see the signed-in user on the top right. Then I sign out, this time the sign-out can work.

I try to debug the problem:

  • If I modify const storage = new CrossStorageClient("https://www.funfun.io/htmls/hub.html", {}); to const storage = new CrossStorageClient("https://www.funfun.io/htmls/hub.html", { 100000 }); in the code, the sign-out (without reloading the page) will go infinite.
  • The url of the add-in is https://v6.10studio.tech/#/ai-formula-editor-addin, which we can launch in a browser as well. We can sign in with Google and sign out without this problem.

Does anyone know what may be the cause of the problem in the Excel add-in?

Best use cases

@danielstjules I'm sure many many hours were put into this project and it looks very interesting. I've used localStorage extensively and I'm a big Zendesk fan. However, I can't quickly identify the pain that cross-storage is relieving.

Perhaps you could incorporate some use cases into the README that explain scenarios where cross-storage would solve a big problem vs using the existing alternative.

Thank you!

Multiple iFrames on same page to the same Hub

Hi, I am running into behavior with CrossStorage where if you try to initialize multiple CrossStorageClients from the same webpage that connect to the same Hub, it creates multiple unique iframes on the page. I was wondering if this behavior was desired, or if it would be possible to make it so that if the current webpage already has an iframe connecting it to the target Hub, any future instances of CrossStorageClient on the same page will use the existing iframe instead of creating their own.

This problem arises because a particular component I am currently developing creates a CrossStorageClient per instance, but the same webpage may already have an iframe linked to that hub.

I would also be willing to write this PR. Please let me know your thoughts, thank you for your time!

Main file as client.js

Would it be possible to set the main file as client.js? Currently running into issues on our suite of projects that use Wiredep that are unable to load it in without setting an override for the main file in our bower.json's.

Zuul test report an error for "del"

I'm getting this :
capture d ecran 2018-10-10 a 10 26 14

This seems to be because of beforeEach hook here which does :

    beforeEach(function(done) {
      cleanup(done);
    });

    var cleanup = function(fn) {
      storage.onConnect().then(function() {
        return storage.del('key1', 'key2');
      })
      .then(fn)
      ['catch'](fn);
    };

But in this test-case, storage doesn't have permission to delete.

Uncaught TypeError: Cannot read property 'appendChild' of null

I dont know what I'm doing wrong I followed the example and I'm getting :

Uncaught TypeError: Cannot read property 'appendChild' of null

On the Hub I put :

CrossStorageHub.init([
   {origin: /:\/\/(www\.)?mysite.com\/something\/myapp?     my.tabName=01rf0000000D4nF#!\/dashboard$/, allow: ['get', 'set', 'del']}
]);

And for the Client I put:

var storage = new CrossStorageClient('https://mysite.com/something/myapp?my.tabName=01rf0000000D4nF#!/dashboard');
    var setKeys = function () {
      return storage.set('newUserData', 'foo', 9000)
      .then(function() {
        return storage.get('key2', 'bar');
      });
    };
    storage.onConnect()
    .then(setKeys)
    .then(function() {
      return storage.get('key1');
    }).then(function(res) {
      console.log(res); // 'foo'
    })['catch'](function(err) {
      console.log(err);
    });

Its not showing the last bit of code but I got it right from the example

Use as a node\browserify npm module

There's an option to install as an npm-module, but did anyone actually tried to use it from as a node-module from browserify? It's not possible since it's not exporting anything from the root index.js

getOrigin returns :// in IE9

_getOrigin method of CrossStorageClient return :// in IE9 in the following lineorigin = uri.protocol + '//' + uri.host; because uri.protocol is : and uri.host empty string.
Why not to use origin and host of window.location if it's available, and as a fallback, use current implementation?

"get" method doesn't return data

Hi, thanks for the great library.

I've been set my
Hub:

     CrossStorageHub.init([
      { origin: /.*account.mydomain$/, allow: ['get', 'set', 'del', 'getKeys'] },
      { origin: /.*site1.mydomain$/, allow: ['get'] },
      { origin: /.*site2.mydomain$/, allow: ['get'] }

    ]);

Client for account.mydomain

  var storage = new CrossStorageClient('http://account.mydomain/hub.html');

When I set the key

 storage.onConnect()
        .then(function () {
            storage.set('userData', JSON.stringify(value));
        }).then(function (res) {
            console.log(res);
        }).catch(function (err) {
            console.log(err);
        });

It works perfectly, but when I'm trying to get this key value the result is always undefined

 storage.onConnect()
        .then(function () {
            storage.get('userData');
        }).then(function (res) {
            console.log(res);
        }).catch(function (err) {
            console.log(err);
        });

What am I doing wrong?
Thank you for any help!

Not working with the modern browsers if third-party cookies are blocked

When I tried running the example given within the repo it is giving me this error.

Error: Closing client. Could not access localStorage in hub.

Google Chrome Version - 90.0.4430.212 (Official Build) (x86_64)

Also, this seems legit to me as soul purpose of third-party cookie blocking is it should block any kind of data access in cross origins. There can't be any loophole to that.

del not working when set is working

Hi! Thanks for this great lib!

I have two synced apps.

App1 is successfully setting localStorage to App2.
App2 is successfully setting localStorage to App1.
But:
App2 is failing to remove localStorage for App1.

Relevant code:
App1 inits CrossStorageHub like this:

CrossStorageHub.init([
  { origin: config.externalApp, allow: ['get', 'set', 'del', 'getKeys', 'clear'] },
]);

config.externalApp is my app url since it work for the setter I'll assume it's properly defined.

App2 sets localStorage to App1 like this: (THIS WORKS!)

const crossStorage = new CrossStorageClient(config.externalAppUrl);
crossStorage.onConnect().then(() => crossStorage.set('edc_user', JSON.stringify(user)));

But, App2 fails to remove localStorage from App1. I am trying this:

const crossStorage = new CrossStorageClient(config.externalAppUrl);
crossStorage.onConnect().then(() => crossStorage.del('edc_user'));

location.reload();

I'll again assume config.externalAppUrl is properly defined since it works for the setter.
I have added the location.reload() below to ask, can it be that the location.reload() I execute after log out interrupts the delete? It's my only guess on what may be wrong right now.

What am I doing wrong?
Thank you for any help!

Error: CrossStorageClient could not connect

I'm trying to upgrade the client and hub to the latest version and getting the timeout error:

Error: CrossStorageClient could not connect

Any pointers as to what it could be? I double checked that the files are loading correctly (including the es6-promise). And the permissions are unchanged from the previous version.

Any pointers as to what else could cause it?

Change request: Is it possible to make the error message more specific as to why it can't connect?

While enabling this functionality in extension, my script is executing multiple times.

multiplemyscript
multiplepostmessageapi

Initialization in myScript.js

xdLocalStorage.init(
{
iframeUrl:'https://rawgit.com/ofirdagan/cross-domain-local-storage/master/app/views/cross-domain-local-storage.html',
initCallback: function () {
console.log('Got iframe ready');
xdLocalStorage.setItem('check', 'no callback');
}
}
);

Manifest:-

"content_scripts":[
{
"matches": ["://.com/*"],
"css": ["css/main.css"],
"js": ["js/background.js","js/jq.js","js/xdLocalStorage.min.js","js/myScript.js"],
"html":["html/popup.html"],
"all_frames": true
}]

Failed to execute 'postMessage' on 'DOMWindow'

I have several apps to support with same login details.
When client page is trying to communicate to target hub page i am getting following error:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:3001') does not match the recipient window's origin
i have client setup as
CrossStorageHub.init([
{origin: /localhost:3000$/, allow: ['get', 'set', 'del', 'getKeys', 'clear']},
{origin: /localhost:3001$/, allow: ['get', 'set', 'del', 'getKeys', 'clear']},
{origin: /localhost:3002$/, allow: ['get', 'set', 'del', 'getKeys', 'clear']},
{origin: /localhost:3003$/, allow: ['get', 'set', 'del', 'getKeys', 'clear']},
{origin: /localhost:3004$/, allow: ['get', 'set', 'del', 'getKeys', 'clear']},
{origin: /localhost:3005$/, allow: ['get', 'set', 'del', 'getKeys', 'clear']},
{origin: /localhost:3006$/, allow: ['get', 'set', 'del', 'getKeys', 'clear']},
{origin: /localhost:3007$/, allow: ['get', 'set', 'del', 'getKeys', 'clear']},
{origin: /localhost:3008$/, allow: ['get', 'set', 'del', 'getKeys', 'clear']}
]);

image

Please help me i am not able to identify the issue

Storage update event

Send an update message an let the application create a trigger (so when another tab changes it the other can detect this)

window.addEventListener('storage', function(e) {
  window.parent.postMessage('cross-storage:updated', '*');
});

CrossStorageClient could not connect in IE 11

I'm debugging a website on my machine with Windows and Windows Subsystem for Linux.

I use cross-storage in my website. I can launch the website https://localhost:3000/sign under Chrome, whereas in IE it raises an error CrossStorageClient could not connect, which blocks the page.

No error in Chrome:
enter image description here

CrossStorageClient could not connect in IE
enter image description here

In the client side, it seems that it is new CrossStorageClient(...) that raises the error.

const storage = new CrossStorageClient(`https://localhost:3000/htmls/hub.html`, {}); 

export async function getSignToken() {
  await storage.onConnect();

If I open https://localhost:3000/htmls/hub.html in IE in a tab, it shows a problem of security certificate, I could click on Go on to the webpage (not recommended) to continue. (The CrossStorageClient could not connect error of the client side is still raised regardless of this).
enter image description here

Here is hub.html on the server side:

<!doctype html>
<head>
  <title>Production Cross Storage Hub</title>
</head>
<body>
  <script type="text/javascript" src="/javascripts/hub.js"></script>
  <script>
    CrossStorageHub.init([
        {origin: /:\/\/localhost(:[0-9]*)?$/, allow: ['get', 'set', 'del']},
        {origin: /\.10studio.tech$/, allow: ['get', 'set', 'del']},
        {origin: /:\/\/(www\.)?10studio.tech$/, allow: ['get', 'set', 'del']}
    ]);
  </script>
</body>
</html>

So, does anyone know how to fix this CrossStorageClient could not connect error?

SCRIPT5: Access is Denied in IE10

Hi,

I'm getting a very weird error in IE10, which is "SCRIPT5: Access is Denied". I hosted my the example in this repository on GoogleDrive. I need both IE10 and HTTPS.

Client1
Client2
Hub

I will get that error when I first open the client, but it works fine if I refresh the page. It also works perfectly on my friend's laptop (without refreshing), but we have the same IE security level settings.

Thanks in advance.

Leo

Is this package still maintained?

Hello

I came across this package. Is it actively maintained? I would like to use it for a website builder-kit to share data across different domains.

Thanks

TypeError: this._installListener is not a function

Using ReactJs I have next issue: TypeError: this._installListener is not a function error in client.js:52

const crossStorageClient = require('cross-storage').CrossStorageClient;
const myUrl = 'http://localhost:3456/hub.html';
...
 componentDidMount() {
    const storage = crossStorageClient(myUrl);
    storage.onConnect()
      .then(() => storage.get('cool_prop'))
      .then((res) => {
        console.log(res);
      })
      .catch(err => console.log(err));
  }
...

hard-coded versioning in dist

The hard-coded version in the name of the file after bower update when version is updated with break path specified in index.html

Support for Different Storage via Adapter

Hi, I was wondering if it would be possible for CrossStorageHub to be able to support being initialized with different types of storage (i.e. indexedDb, WebSQL), rather than solely using localStorage. The reason for this is that localStorage may not be desired by users because of it's limited storage capacity. My thoughts were that this would be implemented via an Adapter and localStorage will be the default storage option when a different one isn't specified, so that this change will not be breaking for existing users of cross-storage. Would be willing to write this PR as well. Please let me know your thoughts, thanks!

Doesn't check if document is ready.

I am curious why there isn't a build-in check on the document.readyState?
This means that we(developers that really love your solution) have to built in checks for that ourselves.. the point is that I have an application where I really want to initialize a class that use's this storage just as soon as possible(most of the times, before document.readyState === 'interactive'.

I think this would be an addition on your library making it easier to implement..

If necessary I can create PR for this :)

storage.get returns "null" on IOS Chrome

When I am on desktop browser I can retrieve the key from the hub correctly but when I open the web page on IOS Chrome it returns "null".

It also works on IOS Safari.

Updating storage

Is there anyway i can update the storage?

As of now we call below method initially and when value updated

menuService.prototype.setMenuStructureInLocalStorage = function (menuStructureKey, menuStructure) {

    var crossDomainStorage = new CrossStorageClient('localstoragehub.html');
    var setCrossDomainStorageKeys = function () {
        return crossDomainStorage.set(that.constants.MENU_STORAGE_KEY.COMBINED_MENU_STRUCTURE_XT, menuStructure);
    };
    crossDomainStorage.onConnect()
    .then(setCrossDomainStorageKeys);
};

But it does not update it.. It always has old values

It's not feasible now.

2024.01.25
Via web storage on iframe is not feasible
Currently, common browsers are not working, and they have all been quarantined

Angular2 with Webpack

I'm trying to get the cross-storage client to work with webpack but I keep getting the following error:

Unhandled Promise rejection: CrossStorageClient is not defined ; Zone: <root>

I tried require('cross-storage').CrossStorageClient; and import './node_modules/cross-storage/dist/client.min.js'; in my webpack.config but got the same error.

Any ideas would be great.

Option or methods to skip serialization

We're trying to use this over at NPR as a drop-in solution to access and set localstorage variables used for analytics from the sub-domains we use for special projects. I love the overall design of the library and the high quality of the code, especially the use of ES6 promises.

However, it doesn't work as a drop-in solution because of the choice to serialize the data in and out of localstorage. Because my team and our projects don't have control over how those variables are set on our parent website and nobody thought to adopt cross-storage when they originally decided to use LocalStorage to stash this information, we can't use the library without modification.

For now, we're going to maintain a fork which skips the json serialization and directly sets/gets the values out of LocalStorage on the hub. But I'm curious if you'd be open to a initialization option that skips the serialization or alternate get/set methods (getDirect?) that accomplish the same. Since we're forking anyway, we could easily make such a thing and submit a pull request.

I suspect this would help spur adoption, because we can't be the only ones who need to retrofit a cross domain storage solution into an existing ecosystem of sites where the choice of storage format is out of their control.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.