简体   繁体   中英

How to repeat this code for all tabs? Chrome Extension

I am trying to build a chrome extension that runs the following when I click a button on popup.html:

  1. gets and reads the urls of each tab one by one
  2. if the url starts with " https://www.linkedin.com/company/ ", gets the company ID right after "company/". (The url usually looks like this: https://www.linkedin.com/company/164233?trk=prof-exp-company-name so in this case for example, I would like to get "164233") Then it should create a new tab with the following url: https://www.linkedin.com/vsearch/p?f_CC=164233

The following codes successfully do what I want for the current tab only. I want the extension to do it for all tabs when I click 'btn2'.

How can I repeat it? With a for loop? Thanks!

document.addEventListener('DOMContentLoaded', function (){
        document.getElementById('btn2').addEventListener('click', printurl)
});

printurl = function(){
chrome.tabs.query({
    active: true,
    lastFocusedWindow: true
}, function(tabs) {


    // and use that tab to fill in out title and url
    var query = tabs[0].url;
    var companyId = query.slice(33, 41);
    var companyId2 = companyId.replace( /\D/g, '');

    saeurl = 'https://www.linkedin.com/sales/search?pivotType=EMPLOYEE&pivotId=' + companyId2;
    chrome.tabs.create({url: saeurl, selected:false})

})
}

If I've understood what you're trying to do correctly, you need to make a few changes. Firstly, if you want all tabs then you don't want to query for active or lastFocusedWindow .

Once you've fixed that issue you should get all tabs, at which point you need to complete your logic for each tab in tabs .

chrome.tabs.query({}, function(tabs) {

    for(var i = 0; i < tabs.length; i++) {
        // and use that tab to fill in out title and url
        var query = tabs[i].url;
        var companyId = query.slice(33, 41);
        var companyId2 = companyId.replace( /\D/g, '');

        saeurl = 'https://www.linkedin.com/sales/search?pivotType=EMPLOYEE&pivotId=' + companyId2;
        chrome.tabs.create({url: saeurl, selected:false})
    }

})

It's also worth thinking about the logic you're using to extract the company ID from the URL. Your current logic relies on the length of the ID, which could change. Take a look at this gist which shows a few different ways of parse URIs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM