我正在構建一個 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
uj5u.com熱心網友回復:
不清楚您嘗試了什么,但您可以將這些值添加到現有回圈中陣列中的物件,然后在第二個回圈中對該陣列進行排序。因為 executeScript 是異步的,所以您需要等待第一個回圈完成,這意味著決議承諾串列,然后按視頻長度對串列進行排序,然后移動選項卡。
這是我為 MV3 想到的。可能有更干凈的方法來做到這一點(我對此很陌生):
*編輯:小幅編輯以清理代碼組織。附加功能到操作(即,在單擊 Chrome 擴展圖示按鈕時運行)。
彈出視窗.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 });
}
}
清單檔案.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/*"
]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/365063.html
