正在构建chrome扩展,以便按DOM元素对打开的选项卡进行排序



我正在构建一个chrome扩展。目标是按视频持续时间(从低到高(对youtube中所有打开的选项卡进行排序。

我从这个GitHub项目中找到了这段代码,在本教程中进行了解释:

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});
}
});

此代码非常适合按字母顺序排序。不过,我想将其调整为按视频持续时间排序。

所以我写这个文件是为了从所有打开的选项卡中获取视频持续时间,但仍然无法访问";排序或移动标签";部分

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>');
});
}
});
});

输出(视频持续时间以秒为单位(-(出现在popup.html中(:

1229.041
187.501
510.581
609.941
1473.821
955.481
5464.281
59.201
1787.701
1523.941

目前还不清楚您尝试了什么,但您可以将这些值添加到现有循环中数组中的对象中,然后在第二个循环中对该数组进行排序。因为executeScript是异步的,所以您需要等待第一个循环完成,这意味着解析一个promise列表,然后根据视频长度对列表进行排序,然后移动选项卡。

以下是我为MV3设计的。可能有更干净的方法可以做到这一点(我对此还很陌生(:

*编辑:对已清理的代码组织进行小的编辑。将功能附加到操作(即,单击Chrome扩展图标按钮即可运行(

popup.js


chrome.action.onClicked.addListener(sortTabsbyDuration);
async function sortTabsbyDuration() {
async function createListEntry(tabId, i) {
return new Promise((resolve) => {
if (/.youtube.com/watch?/.test(tabs[i].url)) {
chrome.scripting.executeScript(
{ target: { tabId: tabId }, func: getYouTubeLength, args: [tabId] },
(returnValue) => {
resolve(returnValue[0].result);
}
);
} else {
resolve({
tabId: tabId,
vidLength: 9999999999,
});
}
});
}
function getYouTubeLength(aTab) {
let vidLength = document.querySelector("video").duration;
if (!vidLength) {
vidLength=1;
}
return {
tabId: aTab,
vidLength: vidLength,
};
}
// MAIN:
const tabs = await chrome.tabs.query({ currentWindow: true });
let promiseList = [];
for (var index = 0; index < tabs.length; index++) {
promiseList.push(createListEntry(tabs[index].id, index));
}
const promisesFinished = Promise.all(promiseList);
const sortedList = (await promisesFinished).sort((a, b) => {
return a.vidLength - b.vidLength;
});
console.log(sortedList);
for (let index = 0; index < sortedList.length; index++) {
await chrome.tabs.move(sortedList[index].tabId, { index: index });
}
}

manifest.json

{
"manifest_version": 3,
"name": "Sort Your Tubes",
"version": "0.0.0.2",
"action": {
"default_title": "Click to sort YouTube videos by video length."
},
"background": {
"service_worker": "popup.js"
},
"permissions": [
"tabs",
"scripting"        
],
"host_permissions": [
"*://www.youtube.com/*"        
]
}

最新更新