xx3004
xx3004

Reputation: 780

How to detect tabs change URLs or tabs create on Google Chrome Extension?

I have a question about writing Google Chrome Extension. My goal now is to detect that if a tab is created or a URL of a tab has been changed.

Practically, I want to insert a dictionary .js from a link online to any webpage on Chrome, and the script will run as background.html. For example, if you open the browser and go to your homepage, it will run the script to insert dictionary.js into that page. When a new tab is created or a new page is open, it will run the script too. And when people change tab's url, it will run the script too. How do I detect if the tab changes in such situations? Ok, here is my ... code, i guess, to explain that.

chrome.someFunctionThatDetectTheSituationsAbove(function() {
    insertDictionaryScript();//I'd love to have the script of detection, not the insertDictionaryScript();
}

I would appreciate for any idea. Thank you. :P.

[x]

Upvotes: 30

Views: 45124

Answers (5)

Rohit Sharma
Rohit Sharma

Reputation: 605

To detect the tab change in google chrome extensions:

In your background script.js add the below code:

chrome.tabs.onActivated.addListener(function() { 
    chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
        var currentURL = tabs[0].url;
        console.log(currentURL); 
    })
});

Upvotes: 3

Sindar
Sindar

Reputation: 10839

Just add this on your background.js :

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    insertDictionaryScript();
});

chrome.tabs.onCreated.addListener(function(tab) {         
   insertDictionaryScript();
});

Upvotes: 69

serg
serg

Reputation: 111265

What you are describing is called a content script. You don't need any coding for that, just make a declaration in the manifest file. More about content scripts here.

Upvotes: 11

kagali-san
kagali-san

Reputation: 3082

There's also onActivated event:

chrome.tabs.onActivated.addListener(function(tabId, changeInfo, tab) {
   insertDictionaryScript();
});

Upvotes: 15

Can't Tell
Can't Tell

Reputation: 13426

You can detect new tab creation by adding a listener to the onCreated event.

You can detect the url change of the tab by adding a listener to the onUpdated event.

Upvotes: 4

Related Questions