Search code examples
javascriptgoogle-chromegoogle-chrome-extension

Write a chrome extension to console.log the active tab URL whenever a new page is loaded


I want to write a chrome extension which records the current active tab URL every time a new site is loaded and send it to a server for further use. So far I have managed to write the following code: manifest.json

{
    "manifest_version": 2,
    "name": "Currenturl",
    "description": "Fetches current tab url.",
    "version": "0.1",
    "author": "Tarun Khare",
    "browser_action": {
        "default_icon": "icon.png",
        "default_title": "Just observing your current url."
    },
    "permissions": ["tabs", "activeTab"],
    "background": {
        "scripts": ["content.js"],
        "persistent": false
    }
}

content.js

chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
    var url = tabs[0].url;
    console.log("hello: "+url);
});

I am using background scripts since chrome.tabs doesn't work in content scripts. But this extension is not printing anything in chrome console. What is the issue?


Solution

    1. Rename content.js to background.js since this is a background script
    2. Use chrome.tabs.onUpdated listener
    3. Look at the correct console: Where to read console messages from background.js?

    chrome.tabs.onUpdated.addListener((tabId, change, tab) => {
      if (change.url) {
        console.log(change.url);
      }
    });
    

    It'll report the URL changes in all tabs.
    You can also limit the processing to only the active tab by adding a check for tab.active property.