Home > Enterprise >  Use Javascript to get current tab url
Use Javascript to get current tab url

Time:11-25

I am trying to create a google extension that keeps track of the current and previous tab URLs a user visits. Is there a way to use Javascript to have the chrome extension run in the background check the current tab and return the URL?

My current HTML:

   <body>
       <div class="container">
           <h2> Current Tab </h2>
           <div id = "current_url"></div>
           <h2> Previous Tab </h2>
           <div id = "previous_url">  </div>
       </div>

   </body>

I tried doing:

document.getElementById("current_url").innerHTML = window.location.href;

but it does not update when I switch to a new tab.

CodePudding user response:

You can use chrome.tabs.query():

"permissions": [ ...
   "tabs"
]

This requires that you request access to the chrome.tabs in your extension manifest file:

chrome.tabs.query({ active: true, lastFocusedWindow: true }, tabs => {
    let url = tabs[0].url;
    // Do something with url
});

The lastFocusedWindow property is used when you want to access the current tab that the user is focused into. You can also use currentWindow: true when you want to get the window where your extension's code is currently executing.

API Reference: https://developer.chrome.com/docs/extensions/reference/tabs/#method-query

  • Related