Share cookies or local storage data between cross domain in Angular ?

www.internetkatta.com

 

Hello Am Avinash

- @aviboy2006

 

www.example.com​
abc.example.com​

Agenda :

  • What is cookies or local storage data ?

  • Why it  is required to share ? 

  • How can share it between subdomain or cross domain ?

  • Demo

  • Discussion (Q/A)

@aviboy2006

What is cookies/local storage data ? ?  🤔

  • HTTP Cookie - is a small piece of data stored on the user's computer

  • Local storage - The localStorage properties allow to save key/value pairs in a web browser.

@aviboy2006

Why it is required to share ?

@aviboy2006

  • When two domain share same resources like one is www.example.com and one is customer.example.com

  • Two domain rights with same owner or accessible

  • Avoid multiple times resource access or fetch if it duplicate across two subdomain or cross domain

  • Major use case is when login to one domain and access to all subdomains 

How to share those ? 

@aviboy2006

Sender Code

@aviboy2006

HTML Code

function postCrossDomainMessage(msg) {
  var win = document.getElementById('ifr').contentWindow;
  win.postMessage(msg, "http://example.com/");
}
var postMsg = {"login": "user"}; // this is just example
postCrossDomainMessage(postMsg);




<iframe style="display:none;" src="http://example.com/getlocalstorage.html" id="ifr"></iframe>

Javascript Code

Receiver Code

@aviboy2006

Text

var PERMITTED_DOMAIN = "http://example.com";
/**
 * Receiving message from other domain
 */
window.addEventListener('message', function(event) {
    if (event.origin === PERMITTED_DOMAIN) {
        //var msg = JSON.parse(event.data);
        // var msgKey = Object.keys(msg)[0];
        if (event.data) {
            localStorage.setItem("localstorage", event.data);
        } else {
            localStorage.removeItem("localstorage");
        }
    }

});

Demo 

@aviboy2006

Two Angular apps share their login data between them using pub-sub pattern

 

Any Question ? 

@aviboy2006

Reference:

@aviboy2006

  • https://www.internetkatta.com/share-cookies-or-local-storage-data-between-cross-domain

  • https://github.com/aviboy2006/cross-domain-cookie-sharing

  • https://github.com/aviboy2006/cookie-or-localstorage-sharing-in-angular-apps

  • https://en.wikipedia.org/wiki/HTTP_cookie

  • https://www.w3schools.com/jsref/prop_win_localstorage.asp

Thank You !

You can reach out to me here 👇🏻

@aviboy2006

@aviboy2006

https://www.linkedin.com/in/avinash-dalvi-315b021a/

avinashsdalvi@gmail.com

www.internetkatta.com

Made with Slides.com