How to get the currently opened tab's URL in my page action popup?

前端 未结 2 1273
野性不改
野性不改 2020-12-03 00:05

I want to create an extension for automatically logging into my servers. So I created a background page to check the current URL and if it conforms to my URL regex, I\'ll di

相关标签:
2条回答
  • 2020-12-03 00:10

    You can also use promises for a cleaner way of retrieving a tab:

      getCurrentTab().then(function(tab){
        // Do something w/tab
      });
    
      function getCurrentTab(){
        return new Promise(function(resolve, reject){
          chrome.tabs.query({
            active: true,               // Select active tabs
            lastFocusedWindow: true     // In the current window
          }, function(tabs) {
            resolve(tabs[0]);
          });
        });
      }
    
    0 讨论(0)
  • 2020-12-03 00:13

    Use chrome.tabs.query with the following parameters:

    • queryInfo object:
      • active: true - To get the active tab
      • lastFocusedWindow: true - To select the active window
    • callback function:
      This function receives one argument: An array of matched tabs. Since only one window can be active, and one tab within this window, the array has only one element. This element is an object with the Tab signature.

    Code snippet:

    // Do NOT forget that the method is ASYNCHRONOUS
    chrome.tabs.query({
        active: true,               // Select active tabs
        lastFocusedWindow: true     // In the current window
    }, function(array_of_Tabs) {
        // Since there can only be one active tab in one active window, 
        //  the array has only one element
        var tab = array_of_Tabs[0];
        // Example:
        var url = tab.url;
        // ... do something with url variable
    });
    

    The activeTab permission is sufficient for this to work.

    0 讨论(0)
提交回复
热议问题