Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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:

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!

like image 324
ognockocaten Avatar asked Oct 07 '14 14:10

ognockocaten


1 Answers

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'}]}
);
like image 133
ognockocaten Avatar answered Oct 02 '22 16:10

ognockocaten