[英]Chrome Extension: webRequest Redirect to Existing Tab, Without Opening New Tab
When a user opens a certain page, I want to open that page in an existing tab, before a new tab is opened.当用户打开某个页面时,我想在打开新选项卡之前在现有选项卡中打开该页面。 I've tried with webRequest:我已经尝试过 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']
);
I've also tried with webNavigation:我也试过 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 });
});
}
});
Both of these open a new tab that has to be closed, and it causes the browser to jump around between tabs.这两者都会打开一个必须关闭的新选项卡,这会导致浏览器在选项卡之间跳转。
Is there any way to intercept requests before a new tab is opened?有没有办法在打开新标签之前拦截请求?
Thanks!谢谢!
I eventually sorted it out.我最终解决了它。 Here's an approximation of the code:这是代码的近似值:
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'}]}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.