Skip to main content

Command Palette

Search for a command to run...

How to Get the Current Tab URL in a Chrome Extension

Published
3 min read
How to Get the Current Tab URL in a Chrome Extension
M

Easily monetize your browser extensions. Mellowtel is an open-source, ethical monetization engine that respects user privacy and maximizes your revenue.

This guide will show you how to efficiently retrieve the URL of the current tab in a Google Chrome extension using the latest recommended methods.

Prerequisites

  • Basic knowledge of JavaScript and HTML

  • Familiarity with Chrome extension development

Steps to Get the Current Tab URL

  1. Update Your Manifest File

    Ensure your manifest.json file includes the necessary permissions:

     {
       "permissions": [
         "tabs"
       ]
     }
    

    Alternatively, you can use the activeTab permission for a less intrusive approach:

     {
       "permissions": [
         "activeTab"
       ]
     }
    
  2. Use the Chrome Tabs API

    The method to get the current tab URL depends on which part of your extension you're working in:

    a) In a background script (background.js):

     // background.js
    
     // Listen for when a tab is updated
     chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
       // Check if the tab has completed loading
       if (changeInfo.status === 'complete') {
         // Query for the active tab in the current window
         chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
           if (tabs[0]) {
             let currentUrl = tabs[0].url;
             console.log('Current tab URL:', currentUrl);
    
             // Here you can perform actions with the URL, such as:
             // - Sending it to a server
             // - Storing it in chrome.storage
             // - Sending a message to a content script
           }
         });
       }
     });
    

    b) In the JavaScript associated with your popup HTML:

     <!-- popup.html -->
     <!DOCTYPE html>
     <html>
       <head>
         <title>My Extension Popup</title>
       </head>
       <body>
         <div id="url-display"></div>
         <script src="popup.js"></script>
       </body>
     </html>
    
     // popup.js
     document.addEventListener('DOMContentLoaded', function() {
       chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
         if (tabs[0]) {
           let currentUrl = tabs[0].url;
           console.log(currentUrl);
           // Use currentUrl to update popup DOM
           document.getElementById('url-display').textContent = currentUrl;
         }
       });
     });
    

    c) In a content script (content.js):

     // content.js
    
     // Get the current page URL
     let currentUrl = window.location.toString();
     console.log('Current page URL:', currentUrl);
    
     // You can now use this URL for various purposes, such as:
     // 1. Sending it to the background script
     chrome.runtime.sendMessage({action: "reportURL", url: currentUrl});
    
     // 2. Modifying page content based on the URL
     if (currentUrl.includes('example.com')) {
       // Perform some action specific to example.com
     }
    
  3. Handle the URL

    Once you have the URL, you can use it as needed in your extension.

Important Notes

  • Permission Choice:

    • Use "tabs" permission if you need broad access to tab information.

    • Prefer "activeTab" if you only need access when the user explicitly interacts with your extension, as it's less intrusive.

  • Window Focus:

    • currentWindow: true uses the window where your extension code is running.

    • lastFocusedWindow: true uses the most recently focused window, which may be different if the user has switched windows.

  • Error Handling: Always check if the tab exists before accessing its properties.

  • Asynchronous Nature: Remember that chrome.tabs.query is asynchronous. Always use the URL inside the callback or use async/await.

Best Practices

  • Handle potential errors, such as when tabs API is not available

  • Consider using async/await for cleaner code if working with newer Chrome versions

  • Be aware of the context (background, popup HTML, or content script) when accessing the URL

  • Respect user privacy and handle URL data securely

More from this blog

M

mellowtel

18 posts