Skip to content

Instantly share code, notes, and snippets.

@alonronin
Last active June 20, 2019 11:04
Show Gist options
  • Save alonronin/2256c2a53d73ef3d6cd92c84a7808087 to your computer and use it in GitHub Desktop.
Save alonronin/2256c2a53d73ef3d6cd92c84a7808087 to your computer and use it in GitHub Desktop.
Cross Domain LocalStorage

Cross Orrigin LocalStorage

Get access to LocalStorage on Cross-Origin Domains.

Usage

Put the iframe.html in your remote domain.

(async () => {
  const ls = crossStorage('https://example.com/iframe.html');

  await ls({ action: 'set', key: 'myKey', value: 'myValue' })';

  const value = await ls({ action: 'get', key: 'myKey' });

  // value: myValue
})()
<script>
window.addEventListener(
'message',
e => {
if (e.origin === location.origin) return;
const { action, key, value } = e.data;
if (action === 'set') window.localStorage.setItem(key, value);
if (action === 'get') {
const data = window.localStorage.getItem(key);
window.parent.postMessage(data, '*')
}
if (action === 'remove') window.localStorage.removeItem(key);
if (action === 'clear') window.localStorage.clear();
},
false
);
</script>
const crossStorage = src => ({ action = 'set', key, value }) =>
new Promise(resolve => {
const iframe = document.createElement('iframe');
const clean = (data) => {
setTimeout(() => {
document.body.removeChild(iframe);
resolve(data);
});
};
iframe.src = src;
iframe.style = {
border: 0,
width: 0,
height: 0,
position: 'absolute',
top: 0,
left: 0
};
document.body.appendChild(iframe);
iframe.addEventListener(
'load',
e => {
const win = iframe.contentWindow;
win.postMessage({ action, key, value }, '*');
if(action === 'get') {
window.addEventListener(
'message',
e => {
if (e.origin === location.origin) return;
return clean(e.data);
},
{ once: true },
false
);
}
clean();
},
{ once: true },
false
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment