2015-04-12 124 views
1

早上好, 我正在嘗試製作此Chrome擴展程序,該擴展程序將關閉與已打開的選項卡的域相匹配的每個新選項卡。我一直試圖關閉,因爲我得到了關閉任何新的選項卡,完全匹配已打開的標籤網址。關閉與已打開的選項卡域匹配的所有新選項卡

這是我到目前爲止的腳本。

chrome.tabs.onCreated.addListener(function(newTab) { 
    chrome.tabs.getAllInWindow(newTab.windowId, function(tabs) { 
     var duplicateTab = null; 
     tabs.forEach(function(otherTab) { 
      if (otherTab.id !== newTab.id && otherTab.url === newTab.url) { 
       duplicateTab = otherTab; 
      } 
     }); 
     if (duplicateTab) { 
      chrome.tabs.update(duplicateTab.id, {"selected": true}); 
      chrome.tabs.remove(newTab.id); 
     } 
    }); 
}); 

所以是的,所以基本上如果舉例來說,如果一個TAB1具有開放example.com話,我想這個腳本關閉,無論具有相同的域打開如果該URL不完全匹配任何其他選項卡。

回答

1

您可以使用Regular Expression從otherTab.url中獲取域,並使用.test()方法查看它是否與newTab.url匹配。這是一個快速測試,看起來像你想要的那樣工作。

chrome.tabs.onCreated.addListener(function (newTab) { 
    chrome.tabs.getAllInWindow(newTab.windowId, function(tabs) { 
     var duplicateTab = null; 
     tabs.forEach(function(otherTab) { 
      // Grab the domain from the otherTab 
      var otherDomain = otherTab.url.replace(/(?:(?:http)s?:\/\/)?(.*?\..{2,3}(\..{2})?)(?:.*)/i, '$1'); 
      // Create a new RegEx pattern with it 
      otherDomain = new RegExp(otherDomain, 'i'); 
      // Then test to see if it matches the newTab.url 
      if (otherTab.id !== newTab.id && otherDomain.test(newTab.url)) { 
       duplicateTab = otherTab; 
      } 
     }); 
     if (duplicateTab) { 
      chrome.tabs.update(duplicateTab.id, {"selected": true}); 
      chrome.tabs.remove(newTab.id); 
     } 
    }); 
}); 
+0

似乎包括會更容易。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes –

+0

這正是我想要做的,非常感謝或抽出時間和幫助。由於某種原因,Regex對我來說總是很困難。 –

相關問題