当用户打开某个页面时,我想在打开新标签页之前在现有标签页中打开该页面。我已尝试过webRequest:
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
chrome.tabs.query({ url: 'https://example.com/' },function (tabs) {
chrome.tabs.update(tabs[0].id, { url: details.url, highlighted: true });
})
},
{urls: ['https://example.com/']},
['blocking']
);
我也尝试过使用webNavigation:
chrome.webNavigation.onBeforeNavigate.addListener(function (details) {
if(details.url=="https://example.com/") {
chrome.tabs.query({ url: 'https://example.com/' },function (tabs) {
chrome.tabs.update(tabs[0].id, { url: details.url, highlighted: true });
});
}
});
这两个都打开了一个必须关闭的新标签,它会导致浏览器在标签之间跳转。
在打开新标签页之前有没有办法拦截请求?
谢谢!
答案 0 :(得分:1)
我最终把它整理出来了。这是代码的近似值:
function openMypageInMysite(tab) {
var urlNavigatingTo = tab.url,
matchMysiteUrl = urlNavigatingTo.match(/^https?:\/\/(.*).mysite.com\/?(.*)$/);
if (matchMysiteUrl) {
var pattern = '*://' + matchMysiteUrl[1] + '.mysite.com/*';
chrome.tabs.query({ url: pattern }, function(openTabs) {
var route = '/' + matchMysiteUrl[2];
Mytab = (openTabs[0].id !== tab.id) ? openTabs[0].id : openTabs[1].id;
chrome.tabs.sendMessage(Mytab, { route: route });
chrome.tabs.update(Mytab, { active: true });
chrome.tabs.remove(tab.id);
});
}
}
chrome.webNavigation.onBeforeNavigate.addListener(
function (details) {
openMypageInMysite({id: details.tabId, url: details.url});
},
{url: [{hostSuffix: 'mysite.com'}]}
);