首页 > 解决方案 > oAuth 交换后关闭 Chrome 窗口

问题描述

我有打开一个窗口的代码

let mywindow = window.open("utl", "title", "resizable=yes,width=600,height=400,toolbar=no,titlebar=no,menubar=no,scrollbars=yes");

我想访问窗口的当前 URL,我尝试过:

每次尝试都会返回:

未捕获的 DOMException:阻止具有源“ https://mail.google.com ”的框架访问跨域框架。在评估(评估在 (chrome-extension://dapaeellgmlagjcopljjcfiadalafdil/extension.js:57053:21), <anonymous>:1:10)在 chrome-extension://dapaeellgmlagjcopljjcfiadalafdil/extension.js:57053:21

我正在进行 oAuth 令牌交换,当窗口到达重定向 URI 时,我需要自动关闭窗口。

我可以通过哪些方式实现这一目标?

标签: javascriptdomgoogle-chrome-extensiongmail

解决方案


您可以使用chrome.tabsAPI 执行此操作,这是一个示例:

const orgURL = '<URL>';
chrome.tabs.create({url: orgURL}, createdTab => {
   function updateListener(tabId, tab) => {
     if (tabId == createdTab.id && tab.url !== orgURL) {
        const redirectURL = tab.url;
        // Do something with the redirect URL
        chrome.tabs.remove(tabId); // Close the tab.
        chrome.tabs.onUpdated.removeListener(updateListener);
     }
   }
   chrome.tabs.onUpdated.addListener(updateListener);
});

不要忘记将chrome.tabs权限添加到清单中。

如果您真的想使用新窗口而不是当前窗口中的新选项卡来执行此操作,请查看chrome.windowsAPI。

以下是使用chrome.windowsAPI 的示例:

const orgURL = "<URL>"
chrome.windows.create({ url: orgURL }, win => {
  if (win.tabs.length) {
    const firstTab = window.tabs[0];
    if (firstTab.url !== orgURL) { // the redirect already happen
       const redirectURL = window.tabs[0].url;
       // Do something with the redirect URL
    } else {// the redirect hasn't happen yet, listen for tab changes.
       function updateListener(tabId, tab) => {
         if (tabId == firstTab.id && tab.url !== orgURL) {
           const redirectURL = tab.url;
           // Do something with the redirect URL
           chrome.windows.remove(win.id); // Close the window.
           chrome.tabs.onUpdated.removeListener(updateListener);
         }
       }
       chrome.tabs.onUpdated.addListener(updateListener);
    }
  }
})

推荐阅读