How to Share Local Storage | Session Storage between different domains | With Demo

 Here You can check how to share domain with Local Storage and Session Storage hare data between multiple domains (for example an auth token) can be somehow hard as we all know that all browser side data storage APIs (Localstorage, cookies etc.) are related to one specific domain.

    


Implementation:

1- Create a listener in the iframe that saves the data passed in localStorage

2- Create a listener in the iframe that sends the data back

3- Using postMessage, we invoke the iframe’s saving function from the parent

4- in whatever other domain we ask for the data from the iframe (using postMessage and listening for a response).

Iframe code

Listen to a message event, check the type of action (save or get) if save, it adds an item to LocalStorage, if get: return the data using postMessage

const domains = [
"https://www.domain1.com",
"https://www.domaine2.com"
]
window.addEventListener("message", messageHandler, false);function messageHandler(event) {
if (!domains.includes(event.origin))
return;
const { action, key, value } = event.data
if (action == 'save'){
window.localStorage.setItem(key, JSON.stringify(value))
} else if (action == 'get') {
event.source.postMessage({
action: 'returnData',
key,
JSON.parse(window.localStorage.getItem(key))
}, '*')
}
}

One of the other windows code will save a data

Uses postMessage to send a message event to the iframe.

const data = doSomeThingToGetData()
const iframe = iframe = document.getElementById('iframe-id')
iframe.contentWindow.postMessage({
action: 'save',
key: 'keyForData',
value: data
})

And now any time one of the windows wants to get this data

Send a message event and the listen to a message event that the iframe will send back.

const iframe = iframe = document.getElementById('iframe-id')
iframe.contentWindow.postMessage({
action: 'get',
key: 'keyForData'
})
window.addEventListener("message", messageHandler, false);function messageHandler(event) {
const { action, key, value } = event.data
if (action == 'returnData'){
useData(key, value)
}
}

No comments:

Post a Comment

SQL Commands - essentials

  SELECT # Retrieve data from the database FROM # Specify the table to select data from WHERE # Filter rows based on a condition AS # Rename...

Best for you