Javascript 关闭与已打开的选项卡域匹配的所有新选项卡
早上好, 我正在尝试做这个chrome扩展,它将关闭与已打开选项卡的域相匹配的每个新选项卡。我一直在尝试关闭任何与已经打开的标签url完全匹配的新标签 这是我到目前为止得到的剧本Javascript 关闭与已打开的选项卡域匹配的所有新选项卡,javascript,regex,google-chrome,google-chrome-extension,Javascript,Regex,Google Chrome,Google Chrome Extension,早上好, 我正在尝试做这个chrome扩展,它将关闭与已打开选项卡的域相匹配的每个新选项卡。我一直在尝试关闭任何与已经打开的标签url完全匹配的新标签 这是我到目前为止得到的剧本 chrome.tabs.onCreated.addListener(function(newTab) { chrome.tabs.getAllInWindow(newTab.windowId, function(tabs) { var duplicateTab = null; t
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有openexample.com,那么我希望这个脚本关闭任何其他用相同域打开的选项卡,无论url是否完全匹配 您可以使用从otherTab.url获取域,并使用该方法查看它是否与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);
}
});
});
似乎包含会更容易。这正是我想做的,非常有效,谢谢你,或者抽出时间来帮忙。由于某些原因,正则表达式对我来说一直很难使用。
.addListener
适用于较旧的浏览器。您可能想改用.addEventListener
。