1

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.

2
  • 1
    Use the History API. Commented Nov 25, 2021 at 0:45
  • 2
    Sorry I am new to Javascript. Could you please provide an example of how I can use it to get the current tab url? Commented Nov 25, 2021 at 0:47

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.