2013-03-06 76 views
0

我想让我的扩展在标签标题的末尾附加一个小文本标签(类似于“(Recorded!)”),以向用户指示它已经注意到给定选项卡已被查看。下面的代码似乎在调试器中工作(也就是说,调试器告诉我在if条件完成后tab.title是[tab.title +(Recorded!)],但是chrome中的标签标题不是改变。我是否需要使用代码刷新标签以查看标题中的更改?如果是这样,我怎么做,没有onUpdated侦听器触发器再次?如果不是,我该怎么办?将文本追加到标签标题?

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

回答

1

您必须使用内容脚本才能执行此操作。 chrome.tabs API仅提供只读访问标签的信息。

看来,编程注射(https://developer.chrome.com/trunk/extensions/content_scripts.html#pi)适合您的情况。

因为内容脚本是在一个孤立的世界中执行的(https://developer.chrome.com/trunk/extensions/content_scripts.html#execution-environment),所以您需要将<脚本>注入页面并通过在其中设置document.title来修改标题。

下面是一个例子(替换tab.title = title + ' (Recorded!)';):

chrome.tabs.executeScript(tab.id, {code: 
    "var script = document.createElement('script');" + 
    "script.appendChild(document.createTextNode('" + 
    "document.title = document.title + \" (Recoorded!)\";" + 
    "'));" + 
    "document.body.appendChild(script);"}); 
+0

伟大的作品!谢谢。 – Zhankfor 2013-03-07 16:33:37

1

我用jQuery和它的工作很大。

var title = $(document).prop('title'); 
if (title.indexOf('new prefix') == -1) { 
    $(document).prop('title', 'new prefix - '+title); 
} 

但一定要包括在内容脚本部分的manifest.json的

"content_scripts": [ { 
    "js": [ "jquery-3.1.0.min.js", "myscript.js" ], 
    "matches": [ "http://*/*", "https://*/*" ] 
}]