0

I'm trying to create the Instagram Basic API login experience with a popup instead of opening a new browser tab.

I have it working with the following code, but I'd like to refactor it... unfortunately, I can't seem to get the popup window to act on any event listeners.

Working code with obviously omitted app_id:

const instagramWindow = window.open(
  `https://api.instagram.com/oauth/authorize?app_id=${app_id}&redirect_uri=${encodeURIComponent(
    window.location.href
  )}&scope=user_profile,user_media&response_type=code`,
  "_blank",
  "height=600,width=600"
);

const id = setInterval(() => {
      try {
        if (window.location.origin === instagramWindow.location.origin) {
          if (instagramWindow.location.search.startsWith("?code=")) {
            console.log("code", instagramWindow.location.search.substr(6));
            instagramWindow.close();
            clearInterval(id);
          }
        }
      } catch (e) {}
    }, 50);

I have successfully been able to retrieve the Instagram code... but I don't like the idea of having an interval checking every 50 milliseconds.

I tried the following that I found on Stackoverflow and it doesn't seem to work for me:

instagramWindow.addEventListener("locationchange", () => {
  console.log("We did it!");
});

instagramWindow.history.pushState = (f =>
  function pushState() {
    var ret = f.apply(this, arguments);
    window.dispatchEvent(new Event("pushstate"));
    window.dispatchEvent(new Event("locationchange"));
    return ret;
  })(instagramWindow.history.pushState);

instagramWindow.history.replaceState = (f =>
  function replaceState() {
    var ret = f.apply(this, arguments);
    window.dispatchEvent(new Event("replacestate"));
    window.dispatchEvent(new Event("locationchange"));
    return ret;
  })(instagramWindow.history.replaceState);

instagramWindow.addEventListener("popstate", () => {
  instagramWindow.dispatchEvent(new Event("locationchange"));
});

Unfortunately, it doesn't work...

I tried the following to see if I could at least get a response from the event listener and even this didn't work.

instagramWindow.addEventListener("load", () => {
    console.log("Super simple event listener that exists and should work!");
});

I'm not sure what I'm doing wrong.

David
  • 7,028
  • 10
  • 48
  • 95
  • 3
    Does this answer your question? [How to detect URL change in JavaScript](https://stackoverflow.com/questions/6390341/how-to-detect-url-change-in-javascript) – Pushprajsinh Chudasama Dec 07 '19 at 07:25
  • 1
    That is where I got the solution that apparently works for others. None of the proposed solutions work except the rudimentary one, which seems to copy my approach above with setInterval. – David Dec 07 '19 at 07:26
  • Have you looked at [window.postMessage](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage). Could be an option. – Bibberty Dec 07 '19 at 07:41

0 Answers0