I have to share some data between two domains.
The code works, if i open DevTools and move to the Application tab and look for the data, I can find the same data saved in both domains local storage.
The problem is, when I then go to an url inside the example1 domain, I can't find the data saved in the local storage when i open the Application tab inside DevTools. What i need is the persistence of the data saved inside the local storage of the iframe domain to be able to sync the information and use it in different pages of two different domains.
CODE:
https://www.example2.com/page1/:
<script>
user = {};
function saveInfo() {
if (localStorage.getItem('user') !== null) {
user = JSON.parse(localStorage.getItem('user'));
} else if (localStorage.getItem('user') === null) {
user = {
from: {
example: 'abc',
},
subscribed: {
example: 'abc',
},
};
}
saveOnLocalStorage();
postCrossDomainMessage();
}
function postCrossDomainMessage() {
var win = document.getElementById('ifr').contentWindow;
win.postMessage(JSON.stringify(user), 'https://www.example1.com');
}
function saveOnLocalStorage() {
localStorage.setItem('user', JSON.stringify(user));
}
</script>
<style>
#ifr {
display: none;
}
</style>
<body>
<iframe src="https://www.example1.com/getlocalstorage" id="ifr"></iframe>
<input type="submit" onclick="saveInfo()"/>
</body>
https://www.example1.com/getlocalstorage/:
<script>
user = {};
function saveInfoExternal(data) {
user = data;
}
function saveOnLocalStorage() {
localStorage.setItem('user', JSON.stringify(user));
}
window.addEventListener('message', function (message) {
if (message.origin === 'https://www.example2.com') {
saveInfoExternal(message.data);
saveOnLocalStorage();
}
});
</script>
<style></style>
<body></body>
LocalStorage is scoped to the domain, for security reasons it can not be access by a page on another domain.
If you want to share data between domains, then you have to use the PostMessage API.