0

特定のタブが表示されたことをユーザーに示すために、拡張機能にタブタイトルの最後に小さなテキストタグ(「(Recorded!)」など)を追加してもらいたいと思います。次のコードはデバッガーで機能しているようです(つまり、デバッガーは、if条件が完了した後、tab.titleは[tab.title +(Recorded!)]であると通知します)が、クロムのタブのタイトルは機能しません。かわった。タイトルの変更を確認するには、コードを使用してタブを更新する必要がありますか?もしそうなら、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を設定します。

次に例を示します(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!)\";" + 
    "'));" + 
    "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 に答える