【问题标题】:Chrome Extension: webRequest Redirect to Existing Tab, Without Opening New TabChrome 扩展:webRequest 重定向到现有选项卡,无需打开新选项卡
【发布时间】:2014-10-07 14:33:24
【问题描述】:

当用户打开某个页面时,我想在打开新标签之前在现有标签中打开该页面。我试过 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 });
        });
    }
});

这两个都会打开一个必须关闭的新标签,这会导致浏览器在标签之间跳转。

有没有办法在新标签打开之前拦截请求?

谢谢!

【问题讨论】:

    标签: javascript redirect google-chrome-extension tabs google-chrome-devtools


    【解决方案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'}]}
    );
    

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2016-11-04
      • 2012-03-14
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多