YouTube Uploads Sorter Button

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

目前为 2023-01-28 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube Uploads Sorter Button
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.14.3
  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. chip.text('Sort by Views'); // have to set the text here, after the append
  24. }
  25. }
  26. function getViews(e) {
  27. try {
  28. //console.log(e);
  29. const viewsTitle = $(e).find('a')[2].getAttribute("aria-label");
  30. //console.log(`Found title: ${viewsTitle}`);
  31. if (viewsTitle.search(/No views$/) > -1) // video has no views yet
  32. return 0;
  33. else {
  34. const views = parseInt(/([\d,]+) views( - play Short)?$/.exec(viewsTitle)[1].replace(/,/g, ""));
  35. return views;
  36. }
  37. } catch(err) {
  38. //console.log(err);
  39. return 0;
  40. }
  41. }
  42.  
  43. function sortByViews() {
  44. console.log("Sorting...");
  45. const items = $("ytd-rich-item-renderer");
  46. console.log(`Found ${items.length} videos on the page.`);
  47. //console.log(items);
  48. //console.log(getViews(items[0]));
  49.  
  50. // Array of each parent for a given index.
  51. // e.g. if there are 4 videos in the first row container, the first 4 indexes are that first row
  52. const parents = [...items].map(e => e.parentNode);
  53. //console.log(parents);
  54. const sorted = items.toArray().sort(function(a, b) {
  55. return getViews(b) - getViews(a);
  56. });
  57. for (let item of sorted) {
  58. // Remove item from its parent and append it to the ordered parent
  59. const parent = parents.shift();
  60. //console.log("Parent: ", parent);
  61. //console.log("Removing", item, "from its parent");
  62. item.parentNode.removeChild(item);
  63. parent.append(item);
  64. }
  65. }
  66.  
  67. function waitForLoad(query, callback) {
  68. if (document.querySelector(query)) {
  69. callback();
  70. } else {
  71. setTimeout(waitForLoad.bind(null, query, callback), 100);
  72. }
  73. }
  74.  
  75. waitForLoad("#chips-wrapper", addButton);
  76. })(window.jQuery);