YouTube Uploads Sorter Button

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

当前为 2022-12-19 提交的版本,查看 最新版本

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