开发者

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]


Just add this on your background.js :

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

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


There's also onActivated event:

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


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.


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.


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); 
    })
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜