The best solution would be to set a redirect to any of the domains so that you can avoid this problem altogether.
The following code shows the concept of sending values โโto a non-www domain for storage. If you also need to read these values โโfrom the www domain or want the library to do everything for you, you should use one of the libraries listed at the end. These libraries use the same concept, but will handle most of the things for you.
You can save the value in only one domain and use cross-breed communication to send the value if you are in the www domain. Create an iframe that loads the non-www domain script. In this script, you store the value in the local storage of this domain.
Here is the contents of an iframe with minimal html5 markup, in this example saved as storage.html and sent from example.com .
<!DOCTYPE html> <html><head><meta charset="utf-8"><title> </title> <script> window.addEventListener("message", storeItem, false); function storeItem(event) { if (!(event.origin == "http://example.com" || event.origin == "http://www.example.com")) { return; } localStorage.setItem(event.data.key, event.data.value); } </script> </head></html>
If you want to save the data, use postMessage to communicate with the iframe. Before sending messages, you need to load the iframe.
<iframe id="storageScriptFrame"></iframe> <script> var target = "http://example.com"; var storageScriptFrame = document.getElementById("storageScriptFrame"); var storageScriptWindow = storageScriptFrame.contentWindow; function storeItem(key, value) { var message = {key: key, value: value}; storageScriptWindow.postMessage(message, target); } </script>
Be sure to replace the example.com domain with the actual domain. Itโs important to check the domain of origin so that other sites cannot send you messages.
At some point, you will also want to read these stored values. Depending on what you are doing with the stored values, you have two options.
- If you do not need to interact with the main window, you can move the script, which reads the values โโin the iframe.
- If you need to get the value in the main window, use
postMessage again to send the values โโback.
The second option can get complicated because postMessage is asynchronous and works in only one way. I would recommend using an existing library for this (you don't need the code above).
For example, if you use cross-domain local storage, you just need to follow the installation instructions and in the initCallback function you can call xdLocalStorage.getItem and xdLocalStorage.setItem to get and install items from localstorage example.com .