Search code examples
javascriptdomgoogle-chrome-extensiongmail

Close Chrome window after oAuth exchange


I have code that opens a window

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

I want to access the current URL of the window, I have tried:

  • window.location
  • window.document.url

Every try returns:

Uncaught DOMException: Blocked a frame with origin "https://mail.google.com" from accessing a cross-origin frame. at eval (eval at (chrome-extension://dapaeellgmlagjcopljjcfiadalafdil/extension.js:57053:21), <anonymous>:1:10) at chrome-extension://dapaeellgmlagjcopljjcfiadalafdil/extension.js:57053:21

I am doing an oAuth token exchange, when the window hits the redirect URI, I need the window to be closed automatically.

What are the ways in which I can achieve this?


Solution

  • You can do this using the chrome.tabs API, here is an example:

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

    Don't forget to add the chrome.tabs permission to the manifest.

    If you really want to do this using a new window instead of a new tab in the current window, take a look at the chrome.windows API.

    Here is an example using the chrome.windows API:

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