Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 211
xx3004 Avatar asked Apr 01 '11 00:04

xx3004


People also ask

Can a website detect other tabs?

Modern websites use multiple "event listeners" and can detect every move the user is executing. So, if a user switches the tab or hovers over to another tab, it can gather the data and see whether the user stayed on the web page or not. A website can detect this anomaly by using cookies and IDs.

How do I tell the difference between tabs in Chrome?

To unpin a tab, right-click the tab and select Unpin. To move a tab to a different window, right-click on the tab and point to Move tab to another window. Then select the window you want to move it to. Make sure you're signed in to Chrome with the same profile in both windows.

Can Chrome remember my tabs?

Just right-click in the open space at the top next to the tabs, and then select “Bookmark All Tabs.” You can also press Ctrl+Shift+D on Windows or Cmd+Shift+D on Mac to bookmark all of your tabs. Chrome will create a new folder for all open tabs. You can rename it if you want, and then click “Save.”

How do I get the URL of a new tab in Chrome?

code.google.com/chrome/extensions/tabs.html#method-getSelected The docs state the first parameter is the windowId, if you want to use that in options, or background page, you would need to put in the window id or you will get the current tab your viewing which is undefined, options respectively.


2 Answers

Just add this on your background.js :

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {     insertDictionaryScript(); });  chrome.tabs.onCreated.addListener(function(tab) {             insertDictionaryScript(); }); 
like image 97
Sindar Avatar answered Sep 21 '22 14:09

Sindar


There's also onActivated event:

chrome.tabs.onActivated.addListener(function(tabId, changeInfo, tab) {    insertDictionaryScript(); }); 
like image 44
kagali-san Avatar answered Sep 19 '22 14:09

kagali-san