2013-03-06 79 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://*/*" ] 
}]