Sharing localStorage data between different domains using iframe not working
The script
tag is before the iframe
tag. It is also executed before the iframe
is created. Hence, searching for ifr
returns null
and null
does not have a contentWindow
, which throws an error. You will need to postpone the JS execution after the page load, like this:
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function postCrossDomainMessage(msg) {
var win = document.getElementById("ifr").contentWindow;
win.postMessage(msg, "http://127.0.0.1:5500/");
}
function load() {
var postMsg = { login: "user" }; // this is just example
postCrossDomainMessage(postMsg);
}
</script>
<script src="index.js"></script>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body onload="load()">
<iframe
style="display: none"
src="http://127.0.0.1:5501/getlocalstorage.html"
id="ifr"
></iframe>
<h1>http://127.0.0.1:5500/index.html</h1>
</body>
</html>
Note that the load
function is not executed in the script
tag, only defined. It is the onload
event defined in body
that triggers it.EDIT
The line of localStorage.setItem("localstorage", event.data);
stores an item into localStorage
with the key of 'localStorage'
and the value of [Object object]
, because into localStorage you will store strings. So, you will need to stringify the object that you have. So, you will need to do something like
localStorage.setItem("localstorage", JSON.stringify(event.data));
And you can read from it via
JSON.parse(localStorage.getItem("localStorage"))
Example
Local Storage Cross Domain - Safari disables it by default
You may try Store.JS. As per the docs:
store.js exposes a simple API for cross browser local storage
Use localStorage across subdomains
This is how I use it across domains...
- Use an iframe from your parent domain - say
parent.example
- Then on each
child.example
domain, just do a postMessage to yourparent.example
iframe - All you need to do is setup a protocol of how to interpret your postMessage messages to talk to the
parent.example
iframe.
Related Topics
JavaScript String Array to Object
What Is Firebase Firestore 'Reference' Data Type Good For
Should Github Be Used as a Cdn for JavaScript Libraries
How to Bind Bootstrap Popover on Dynamic Elements
JavaScript Regular Expression to Check for Ip Addresses
Window.Location.Reload with Clear Cache
How to Validate Google Recaptcha V2 Using JavaScript/Jquery
Parse String to Date with Moment.Js
Single Quote Escape in JavaScript Function Parameters
Why Let and Var Bindings Behave Differently Using Settimeout Function
React Jsx: Selecting "Selected" on Selected <Select> Option
What's Wrong with Var X = New Array();
How Does Setinterval and Settimeout Work
How to Pass Data from Child to Parent Component Angular
Understanding JavaScript Promise Object