Search code examples
javascripthtmlreactjs

Send information from one browser window to another


I have a SPA that I cannot leave due to the fact that if the user leaves/refreshes, some information might be lost.

I want to implement the Instagram API, however the API requires that you browse to a different URL, login, receive a code in your URL, and then get redirected back.

Since I cannot do this directly from my site, I must open a new window to do this.

How can I retrieve the code from the URL in a separate window to send back to my site in the original window?

I have looked at websockets (need a server, so no) and WebRTC (on localhost, did not seem to work) already with no luck. Any suggestions?


Solution

  • If the API allows using an iframe, you can watch what's happening inside the iframe or communicate from inside the iframe using parent.instagramLogin(data) (where instagramLogin is a function you defined outside the iframe).

    An alternative option is to automatically close the login tab once the login is finished, and when the main tab is focused again (window.onfocus) send an ajax request to check if the login was completed. (and of course keep checking every time the event fires until you get a result or until it becomes irrelevant.)

    Update:

    I found a reliable way to communicate between open tabs, using BroadcastChannel if supported, otherwise storage event from localStorage. You can find the details here, and someone in this link even made a small library to make it quick and easy.