Zhankfor Zhankfor - 1 year ago 145
Javascript Question

Append text to tab title?

I would like to have my extension append a little text tag (something like "(Recorded!)") to the end of tab titles to indicate to the user that it has noted that a given tab was viewed. The following code seems to work in the debugger (that is, the debugger tells me that tab.title is [tab.title + (Recorded!)] after the if condition completes), but the title of the tab in chrome isn't changed. Do I need to refresh the tab using code in order to see the change in the title? And if so, how do I do that without having the onUpdated listener trigger again? And if not, what should I do?

// get title of updated tab, increment if it has "NYTimes.com" in it (crude equivalent for article)
chrome.tabs.onUpdated.addListener(function(url, changeInfo, Tab)
chrome.tabs.getSelected(null, function(tab)
var title = tab.title;

if (title.indexOf("NYTimes.com") != -1 && changeInfo.status == "complete")
tab.title = title + ' (Recorded!)';
localStorage.setItem('nyt', ++nytCount);

Answer Source

You must use a content script in order to do this. chrome.tabs API only provides read-only access to tabs' information.

It seems that programatically injection (https://developer.chrome.com/trunk/extensions/content_scripts.html#pi) is suitable in your case.

Because content scripts are executed in an isolated world (https://developer.chrome.com/trunk/extensions/content_scripts.html#execution-environment), you'll need to inject <script> into the page and modify the title by setting document.title there.

Here's an example (replace tab.title = title + ' (Recorded!)';):

chrome.tabs.executeScript(tab.id, {code: 
    "var script = document.createElement('script');" + 
    "script.appendChild(document.createTextNode('" +
    "document.title = document.title + \" (Recoorded!)\";" + 
    "'));" + 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download