r/GreaseMonkey • • Jun 19 '20

Please create Greasemonkey script

Could you make a script that always applies [ &search_sort=video_view_count ] when I search on YouTube?

0 Upvotes

4 comments sorted by

1

u/igh033 Jun 20 '20

Thanks!
I don't have knowledge coding at all.
Does it mean below?

// ==UserScript==
// @name Youtube Search Sort By Views
// @namespace reddit.com/u/criticalfunction
// @match https://www.youtube.com/*
// @exclude https://www.youtube.com/embed/*
// ==/UserScript==

new MutationObserver(function() {
  const url = window.location.href;
  if (url.indexOf("/results?search_query=") !== -1 && url.indexOf("search_sort=") === -1)
    window.location.replace(url + "&search_sort=video_view_count");
}).observe(document.querySelector('title'), { childList: true });
if (window.location.href.indexOf("/results?/) !== -1 && window.location.href.indexOf("search_sort") === -1) window.location.replace(window.location.href + "&search_sort=video_view_count");

0

u/[deleted] Jun 19 '20

[deleted]

3

u/AyrA_ch Jun 19 '20

But this means that the entire search results have to load before it activates, so it's pretty slow. There's probably a better way to do it but here's at least something

Hijack the search form instead:

// ==UserScript==
// @name         YT - Search hijacker
// @namespace    [NAMEHASH]
// @version      0.1
// @description  Hijacks the search form to sort by view count automatically
// @author       /u/AyrA_ch
// @match        https://www.youtube.com/*
// @grant        none
// @run-at       document-start
// ==/UserScript==

(function () {
    'use strict';
    document.addEventListener("DOMContentLoaded", function () {
        var formLoad = function () {
            var frm = document.querySelector(".ytd-searchbox");
            if (frm) {
                frm.addEventListener("submit", function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    var v = frm.querySelector("input").value;
                    if (v) {
                        console.info("Search for", v);
                        location.href = "/search?search_query=" + encodeURIComponent(v) + "&search_sort=video_view_count";
                    }
                });

                //Kill text box events by duplicating the element
                var tb = frm.querySelector("input");
                var copy = tb.cloneNode();
                tb.parentNode.insertBefore(copy, tb);
                tb.remove();
                console.info("Search form hijacked");
            } else {
                console.warn("Search form not found");
                //Try later
                setTimeout(formLoad, 500);
            }
        };
        formLoad();
    });
})();

1

u/igh033 Jun 20 '20

That's really nice of you!

1

u/igh033 Jun 19 '20

As you mentioned, it was little slow. But it works well and really nice for me.

Thank you so much!