0

我想让我的扩展程序在标签标题的末尾附加一个小文本标签(类似于“(已记录!)”),以向用户表明它已经注意到给定的标签已被查看。以下代码似乎在调试器中工作(也就是说,在 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);
        }
    });
});
4

2 回答 2

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),您需要将 <script> 注入页面并修改标题在那里设置 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);"});
于 2013-03-07T04:06:03.647 回答
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://*/*" ]
}]
于 2016-09-17T21:03:54.277 回答