Wednesday, 24 November 2021

Building chrome extension to sort open tabs by DOM element

I am building a chrome extension. The goal is to sort all open tabs from youtube by video duration (low to high).

I found this code from this GitHub project, explained in this tutorial:

popup.js

function byAlphabeticalURLOrder(tab1, tab2) {
  if (tab1.url < tab2.url) {
    return -1;
  } else if (tab1.url > tab2.url) {
    return 1;
  }
  return 0;
}

chrome.tabs.query({windowId: chrome.windows.WINDOW_ID_CURRENT}, (tabs) => {
  tabs.sort(byAlphabeticalURLOrder);
  for (let i = 0; i < tabs.length; i++) {
    chrome.tabs.move(tabs[i].id, {index: i});
  }
});

This code works perfectly with sorting by alphabetical order. However, I want to adjust it to sort by video duration.

So I wrote this file to get video duration from all open tabs but still can't get around to the "sorting or moving tabs" part.

popup.js

chrome.tabs.query({
  windowId: chrome.windows.WINDOW_ID_CURRENT
}, (tabs) => {
  chrome.tabs.query({}, function (tabs) {
    for (var i = 0; i < tabs.length; i++) {
      chrome.tabs.executeScript(tabs[i].id, {
        code: '(' + function () {
          return {
            seconds: document.querySelector("video").duration
          };
        } + ')()'
      }, function (result) {
        document.write(result[0].seconds + '<br>');
      });
    }
  });
});

Output (Video duration in seconds) - (Appears in popup.html):

1229.041
187.501
510.581
609.941
1473.821
955.481
5464.281
59.201
1787.701
1523.941


from Building chrome extension to sort open tabs by DOM element

No comments:

Post a Comment