YouTube Uploads Sorter Button

Adds a button to a YouTube channel's videos page which sorts recent uploads by views

目前为 2023-05-08 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube Uploads Sorter Button
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.14.6
  5. // @description Adds a button to a YouTube channel's videos page which sorts recent uploads by views
  6. // @author Lex
  7. // @match *://*.youtube.com/@*
  8. // @match *://*.youtube.com/*/featured
  9. // @match *://*.youtube.com/*/videos
  10. // @exclude-match *://*.youtube.com/watch
  11. // @require https://code.jquery.com/jquery-3.2.1.min.js
  12. // @grant none
  13. // ==/UserScript==
  14.  
  15. (function($) {
  16. 'use strict';
  17.  
  18. function addButton() {
  19. if ($("#sortViewButton").length == 0) {
  20. const chip = $("<yt-chip-cloud-chip-renderer>").attr("chip-style", "STYLE_DEFAULT").attr("id", "sortViewButton").click(sortByViews);
  21. const container = $("#chips-wrapper iron-selector");
  22. chip.appendTo(container);
  23. setTimeout(() => {
  24. chip[0].innerText = "Sort by Views";
  25. }, 0)
  26. }
  27. }
  28. function getViews(e) {
  29. try {
  30. //console.log(e);
  31. const viewsTitle = $(e).find('a#video-title-link')[0].getAttribute("aria-label");
  32. //console.log(`Found title: ${viewsTitle}`);
  33. if (viewsTitle.search(/No views$/) > -1) // video has no views yet
  34. return 0;
  35. else {
  36. const views = parseInt(/([\d,]+) views( - play Short)?$/.exec(viewsTitle)[1].replace(/,/g, ""));
  37. return views;
  38. }
  39. } catch(err) {
  40. //console.log(err);
  41. return 0;
  42. }
  43. }
  44.  
  45. function sortByViews() {
  46. console.log("Sorting...");
  47. const items = $("ytd-rich-item-renderer");
  48. console.log(`Found ${items.length} videos on the page.`);
  49. //console.log(items);
  50. //console.log(getViews(items[0]));
  51.  
  52. // Array of each parent for a given index.
  53. // e.g. if there are 4 videos in the first row container, the first 4 indexes are that first row
  54. const parents = [...items].map(e => e.parentNode);
  55. //console.log(parents);
  56. const sorted = items.toArray().sort(function(a, b) {
  57. return getViews(b) - getViews(a);
  58. });
  59. for (let item of sorted) {
  60. // Remove item from its parent and append it to the ordered parent
  61. const parent = parents.shift();
  62. //console.log("Parent: ", parent);
  63. //console.log("Removing", item, "from its parent");
  64. item.parentNode.removeChild(item);
  65. parent.append(item);
  66. }
  67. }
  68.  
  69. function waitForLoad(query, callback) {
  70. if (document.querySelector(query)) {
  71. callback();
  72. } else {
  73. setTimeout(waitForLoad.bind(null, query, callback), 100);
  74. }
  75. }
  76.  
  77. waitForLoad("#chips-wrapper", addButton);
  78. })(window.jQuery);