1

Firefox WebExtension上工作。Firefox/Chrome擴展程序:如何在創建新選項卡時打開鏈接?

下面的代碼在我打開一個新選項卡時工作,但是當我點擊一個鏈接時它正在更新任何當前選項卡。

如何使用query來選擇只有新標籤?
是否有另一種方法來做到這一點?

/* Load Google when creates a new tab. */ 

function openMyPage() { 
    //console.log("injecting"); 
    chrome.tabs.query({ 
    'currentWindow': true, 
    'active': true 
    // This will match all tabs to the pattern we specified 
    }, function(tab) { 
     // Go through all tabs that match the URL pattern 
     for (var i = 0; i < tab.length; i++){ 
      // Update those tabs to point to the new URL 
      chrome.tabs.update(
       tab[i].id, { 
        'url': 'http://google.com' 
       } 
      ); 
     } 
    }); 
}; 

//Add openMyPage() as a listener when new tabs are created 
chrome.tabs.onCreated.addListener(openMyPage); 

回答

1

tabs.onCreated回調提供一種參數,它是一個對象Tab。你不應該查詢得到它,你已經擁有了它。

function openMyPage(tab) { 
    chrome.tabs.update(
     tab.id, { 
      'url': 'http://google.com' 
     } 
    ); 
}; 

注意,這會不加區別地瞄準新的標籤 - 即使是那些用戶通過「在新標籤中打開鏈接」打開。如果這不是你想要的,你需要額外的邏輯來檢測它是一個新的標籤頁。

使用"tabs"權限,tab對象將具有填充屬性url。您可以使用它來過濾新選項卡。在Chrome中,這應該是chrome://newtab/,在Firefox中它應該是(我沒有測試過)about:homeabout:newtab

相關問題