如何检测窗口网址更改?

时间:2019-12-07 07:22:35

标签: javascript event-handling window dom-events

我试图通过弹出窗口创建Instagram Basic API登录体验,而不是打开新的浏览器选项卡。

我可以使用下面的代码,但是我想对其进行重构……不幸的是,我似乎无法使弹出窗口对任何事件侦听器起作用。

明显省略了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);

我已经能够成功检索Instagram代码...但是我不喜欢每隔50毫秒检查一次间隔的想法。

我尝试了在Stackoverflow上发现的以下内容,但它似乎对我不起作用:

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"));
});

不幸的是,它不起作用...

我尝试了以下操作,以查看是否至少可以从事件侦听器得到响应,即使这样也不起作用。

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

我不确定自己在做什么错。

0 个答案:

没有答案
相关问题