关闭与已打开的选项卡域匹配的所有新选项卡
问题描述:
早上好, 我正在尝试制作此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不完全匹配任何其他选项卡。
答
您可以使用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);
}
});
});
似乎包括会更容易。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes –
这正是我想要做的,非常感谢或抽出时间和帮助。由于某种原因,Regex对我来说总是很困难。 –