1

単純な拡張機能を作成していて、現在のタブを新しい場所に移動したいのですが、このコードは機能しません:

function redirect() {
    console.log("HELLO"); 
    chrome.tabs.getSelected(null, function(tab) {
        var currentURL = tab.url;
        if(currentURL == "http://example.site/"){
            chrome.tabs.create("http://newlocation.site/",tab);
            alert("redirected");
        }
    });
}

chrome.browserAction.onClicked.addListener(redirect);

とにかく、選択したタブのプロパティに関する情報をグーグルで検索することはできません。tab.url「コマンド」のようなものはありますか?つまり、 tab.reload() .. など...

4

1 に答える 1

1

現在のコードを修正した後、現在のタブが指定された URL と一致すると、新しいタブが作成されます。

  1. chrome.tabs.create(object createInfo, function callback)は正しい署名です。
  2. 注:chrome.tabs.getSelected は推奨されなくなりましたchrome.tabs.query

    chrome.tabs.create({url: "http://newlocation.site/"});
    

このコードは意図したとおりに機能します (バックグラウンド スクリプト)。

function redirect() {
    console.log("Querying...");
    chrome.tabs.query({active: true}, function(tabArray) {
        var currentURL = tabArray[0].url;
        // For debugging purposes:
        console.log(currentURL);
        if (currentURL == "http://example.site/") {
            // The next line is the important change
            chrome.tabs.create({url: "http://newlocation.site/"});
            alert("redirected");
        }
    });
}
chrome.browserAction.onClicked.addListener(redirect);

新しいタブを作成するのではなく、現在のタブの URL を変更する場合は、update代わりにcreate次を使用します。

chrome.tabs.update(tabArray[0].id, {url: "http://newlocation.site/"});

ドキュメンテーション

于 2012-04-08T13:58:14.280 に答える