🌐 How to Get the Current Tab URL in a Chrome Extension
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, for a less intrusive approach:
{
"permissions": [
"activeTab"
]
}
2. Use the Chrome Tabs API
The method you use depends on your extension's context:
a) 📦 Background Script (background.js
)
// background.js
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
if (tabs[0]) {
let currentUrl = tabs[0].url;
console.log('Current tab URL:', currentUrl);
}
});
}
});
b) 📄 Popup Script (popup.js
with 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);
document.getElementById('url-display').textContent = currentUrl;
}
});
});
c) 🧠 Content Script (content.js
)
// content.js
let currentUrl = window.location.toString();
console.log('Current page URL:', currentUrl);
// Send to background script
chrome.runtime.sendMessage({action: "reportURL", url: currentUrl});
// Conditionally act on specific URL
if (currentUrl.includes('example.com')) {
// Perform actions for example.com
}
🔄 Handle the URL
Once retrieved, use the URL as needed:
- Store it in
chrome.storage
- Send it to your backend
- Modify page behavior based on URL
⚠️ Important Notes
-
Permission Choice:
- Use
"tabs"
for broad access - Use
"activeTab"
for limited, user-triggered access
- Use
-
Window Focus:
currentWindow: true
refers to the current windowlastFocusedWindow: true
may refer to a different window
-
Error Handling:
Always check iftabs[0]
exists before accessing its properties. -
Async Nature:
Use the URL inside the callback or useasync/await
for modern code.
✅ Best Practices
- Handle potential errors gracefully
- Prefer
async/await
for cleaner code - Be aware of your execution context (background, popup, content)
- Respect user privacy when handling URLs
If this guide helped you better understand Chrome Extensions, share it with other developers and check out more tutorials from the Mellowtel Team!