Skip to content

Commit

Permalink
Merge pull request #19 from MauriceButler/cleanup
Browse files Browse the repository at this point in the history
Resolve data handling to remove JSON.parse / JSON.stringify, sightly …
  • Loading branch information
MatthewLarner authored Feb 3, 2020
2 parents 8085770 + 3b29610 commit 1d608a7
Show file tree
Hide file tree
Showing 14 changed files with 8,272 additions and 5,711 deletions.
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
6 changes: 6 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"tabWidth": 4,
"trailingComma": "all",
"printWidth": 120,
"singleQuote": true
}
31 changes: 20 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,49 +5,56 @@ Use a host to give access to local storage.
Use a guest to gain access to the local storage on a host.

## Install

npm i cross-domain-storage

## Usage

### Host

```javascript
var createHost = require('cross-domain-storage/host');
```

#### host(allowedDomains)

Call with an array of allowed domains.

```javascript
var storageHost = createHost([
{
origin: 'http://www.foo.com',
allowedMethods: ['get', 'set', 'remove']
},
{
origin: 'http://www.bar.com',
allowedMethods: ['get']
}
]);
{
origin: 'http://www.foo.com',
allowedMethods: ['get', 'set', 'remove'],
},
{
origin: 'http://www.bar.com',
allowedMethods: ['get'],
},
]);
```

#### host.close()

```javascript
storageHost.close();
// storageHost will no longer allow access from guests and can no longer be used.
```

### Guest

```javascript
var createGuest = require('cross-domain-storage/guest')
var createGuest = require('cross-domain-storage/guest');
```

#### guest(hostURL)

Create a guest and connect to the host.

Any methods that are called while connecting are queued up and handled seamlessly.

```javascript
// Hosted on http://www.foo.com
var bazStorage = createGuest('http://www.baz.com/accessStorage');
var bazStorage = createGuest('http://www.baz.com/accessStorage');
```

#### guest.get(key, callback)
Expand All @@ -60,6 +67,8 @@ bazStorage.get('fizz', function(error, value) {

#### guest.set(key, value, callback)

_NOTE: The keys and the values in localStorage are always strings thus objects, numbers etc used as keys or values will be automatically converted to strings._

```javascript
bazStorage.set('foo', 'bar', function(error, data) {
// foo is now set to 'bar'
Expand Down
4 changes: 2 additions & 2 deletions getId.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
var prefix = 'sessionAccessId-';
const prefix = 'sessionAccessId-';

function getId(data) {
var id;
let id;

if (data && data.id && ~data.id.indexOf(prefix)) {
id = data.id;
Expand Down
64 changes: 29 additions & 35 deletions guest/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
var crel = require('crel');
var prefix = 'sessionAccessId-';
var getId = require('../getId');
const crel = require('crel');
const getId = require('../getId');

const prefix = 'sessionAccessId-';

function createId() {
return prefix + Date.now();
Expand All @@ -9,21 +10,20 @@ function createId() {
module.exports = function storageGuest(source, parent) {
parent = parent || document.body;

var iframe;
var contentWindow;
var callbacks = {};
var sessionRequests = [];
var connected = false;
var closed = true;
var connectedTimeout;
var isLoaded = false;
let contentWindow;
let callbacks = {};
const sessionRequests = [];
let connected = false;
let closed = true;
let connectedTimeout;
let isLoaded = false;

iframe = crel('iframe', {
const iframe = crel('iframe', {
src: source,
width: 0,
height: 0,
style: 'display: none;',
onload: function() {
onload() {
isLoaded = true;
},
});
Expand All @@ -41,27 +41,21 @@ module.exports = function storageGuest(source, parent) {
openStorage();

function handleMessage(event) {
var response = event.data;
var sessionAccessId = getId(response);
const response = event.data;
const sessionAccessId = getId(response);

if (sessionAccessId === 'sessionAccessId-connected') {
connected = true;
return;
}

if (response.connectError) {
for (var key in callbacks) {
if (callbacks[key]) {
callbacks[key](response.error);
}
}

Object.keys(callbacks).forEach(key => callbacks[key](response.error));
callbacks = {};

return;
}

var callback = callbacks[sessionAccessId];
const callback = callbacks[sessionAccessId];

if (sessionAccessId && callback) {
callback(response.error, response.data);
Expand All @@ -82,22 +76,22 @@ module.exports = function storageGuest(source, parent) {
}

if (!connected && method !== 'connect') {
sessionRequests.push(arguments);
sessionRequests.push([method, key, value, callback]);
}

var id = createId();
const id = createId();

callbacks[id] = callback;

if (isLoaded) {
contentWindow.postMessage(
{
method: method,
key: key,
value: value,
id: id,
method,
key,
value,
id,
},
source
source,
);
}
}
Expand All @@ -122,7 +116,7 @@ module.exports = function storageGuest(source, parent) {
if (connected) {
clearTimeout(connectedTimeout);
while (sessionRequests.length) {
message.apply(null, sessionRequests.pop());
message(...sessionRequests.pop());
}

return;
Expand All @@ -134,9 +128,9 @@ module.exports = function storageGuest(source, parent) {
}

return {
get: get,
set: set,
remove: remove,
close: close,
get,
set,
remove,
close,
};
};
40 changes: 22 additions & 18 deletions host/index.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,39 @@
var getId = require('../getId');
var methods = require('./methods');
const getId = require('../getId');
const methods = require('./methods');

module.exports = function storageHost(allowedDomains) {
function handleMessage(event) {
var data = event.data;
var domain = allowedDomains.find(function (allowedDomain) {
return event.origin === allowedDomain.origin;
});
var id = getId(data);
const { data } = event;
const domain = allowedDomains.find(allowedDomain => event.origin === allowedDomain.origin);
const id = getId(data);

if (!id) {
return;
}

if (!domain) {
event.source.postMessage({
id: id,
connectError: true,
error: event.origin + ' is not an allowed domain',
}, event.origin);
event.source.postMessage(
{
id,
connectError: true,
error: `${event.origin} is not an allowed domain`,
},
event.origin,
);

return;
}

var method = data.method;
const { method } = data;

if (!~domain.allowedMethods.indexOf(method) && method !== 'connect') {
event.source.postMessage({
id: id,
error: method + ' is not an allowed method from ' + event.origin,
}, event.origin);
event.source.postMessage(
{
id,
error: `${method} is not an allowed method from ${event.origin}`,
},
event.origin,
);

return;
}
Expand All @@ -44,6 +48,6 @@ module.exports = function storageHost(allowedDomains) {
window.addEventListener('message', handleMessage);

return {
close: close,
close,
};
};
67 changes: 32 additions & 35 deletions host/methods.js
Original file line number Diff line number Diff line change
@@ -1,44 +1,41 @@
var connectId = 'sessionAccessId-connected',
parseJSON = require('try-parse-json');

function parseJSONValue(value) {
if (value == null) {
return value;
}

var result = parseJSON(value);

if (result instanceof Error) {
result = null;
}

return result;
}
const connectId = 'sessionAccessId-connected';

module.exports = {
get: function (event, data) {
event.source.postMessage({
id: data.id,
data: parseJSONValue(window.localStorage.getItem(data.key)),
}, event.origin);
get(event, data) {
event.source.postMessage(
{
id: data.id,
data: window.localStorage.getItem(data.key),
},
event.origin,
);
},
set: function (event, data) {
window.localStorage.setItem(data.key, JSON.stringify(data.value));
set(event, data) {
window.localStorage.setItem(data.key, data.value);

event.source.postMessage({
id: data.id,
}, event.origin);
event.source.postMessage(
{
id: data.id,
},
event.origin,
);
},
remove: function (event, data) {
window.localStorage.removeItem(data.key, data.value);
remove(event, data) {
window.localStorage.removeItem(data.key);

event.source.postMessage({
id: data.id,
}, event.origin);
event.source.postMessage(
{
id: data.id,
},
event.origin,
);
},
connect: function (event) {
event.source.postMessage({
id: connectId,
}, event.origin);
connect(event) {
event.source.postMessage(
{
id: connectId,
},
event.origin,
);
},
};
Loading

0 comments on commit 1d608a7

Please sign in to comment.