Могу ли я открыть ссылку в целевой/конкретной вкладке браузера?

Я пытаюсь создать расширение для Chrome. это заставит ссылки открываться на определенной целевой вкладке. например, tab[0] или tab[1] или оба для разных категорий ссылок.

Ниже Совместное использование кода расширения, которое открывает всплывающее окно на вкладке. Это для некоторого контекста. но я не очень понимаю.

// background script

// get settings
chrome.storage.sync.get({
// default value
t1pop: true,
t1foc: true
}, function(items) {
t1pop = items.t1pop;
t1foc = items.t1foc;

// open pop-up as a tab
chrome.windows.getCurrent({},function(w){
var mainwindow = w.id;
chrome.windows.onCreated.addListener(function(w){
    if (w.type == "popup" && t1pop == true){
        chrome.windows.get(w.id,{populate:true},function(w){

            chrome.tabs.query({
                active: true,
                windowId: w.id
            }, function (tabs) {
                var t1popUrl = tabs[0].url;
                if (t1popUrl.startsWith('chrome-extension://') == false){
                    chrome.tabs.move(w.tabs[0].id,{windowId:mainwindow,index:-1},function(){
                        chrome.tabs.update(w.tabs[0].id,{active:t1foc /* focus new window or not */});
                    });
                }

            });


        });
    }
});

chrome.windows.onFocusChanged.addListener(function(w){
    chrome.windows.get(w,{},function(w){        
        if (w.type == "normal"){
            mainwindow = w.id;
        }
    });
    });
});


});

Я тщательно искал ответы на свой вопрос в стеке и не получил ответа.Спасибо за помощь.

🤔 А знаете ли вы, что...
JavaScript поддерживает объектно-ориентированное программирование.


580
1

Ответ:

Решено

Я решил это, сохранив идентификаторы предварительно открытых вкладок в массиве. а затем обновить URL-адрес этих вкладок в событии onBeforeRequest

let slots = [false, false, false, false] //will populate with placeholder tabs.
let preventTabCreation = false //will be true once initial tabs are created..
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
    let url = details.url
    let tabNo;
    let tab_id = details.tabId
    if (!slots.includes(tab_id) && preventTabCreation) {
        for(let i = 1; i < slots.length; i++) {
            if (urlinarr(linkTabs[i-1], url)) {
                tabNo = i;
            }
        }
        chrome.tabs.remove(tab_id)
        chrome.tabs.update(slots[tabNo], {url: url, active: true})
        return {cancel: true}
    }
},
{urls: ["<all_urls>"]},
["blocking"]);

в первый раз, чтобы создать вкладки-заполнители, используя этот код.

chrome.browserAction.onClicked.addListener(function() {
  launch()
})

function launch() {
  //using the first tab for google sheets. where the links to be opened are.
  if (!slots[0]) {
    chrome.tabs.create({
      url: "https://docs.google.com/spreadsheets",
      index: 0
    }, function(data) {
      slots[0] = data.id
      startPreventingTabCreation()
    })
  }
  for (let i = 1; i < slots.length; i++) {
    if (!slots[i]) {
      chrome.tabs.create({
        url: chrome.extension.getURL('dummy.html'),
        index: i
      }, function(data) {
        slots[i] = data.id
        startPreventingTabCreation()
      })
    }
  }
}

function startPreventingTabCreation() {
  if (slots.every(x => x != false)) {
    preventTabCreation = true
    chrome.tabs.update(slots[0], {
        active: true
      })
  }
}