javascripthtmlyoutubetampermonkeyuserscripts

How to focus YouTube search suggestions items?


I currently have this code. This opens the YT search in a new tab when you click the middle-mouse button:

(function() {
    'use strict';
 
    var searchIcon = document.getElementById("search-icon-legacy");
    if (searchIcon) {
        searchIcon.addEventListener("mousedown", function(event) {
            event.preventDefault();
            var searchInput = document.getElementsByClassName("ytd-searchbox")[3].value.trim();
            if (event.which === 2 && searchInput) {
                window.open("https://www.youtube.com/results?search_query=" + encodeURIComponent(searchInput), "_blank");
            }
        });
    }
})();

Picture

I'm now trying to focus the search suggestions by middle-clicking them, but I'm struggling because I don't know how to bring them into focus like the search button, which is an element.


Solution

  • if what you want is to open the one of the search suggestions in another tab using a middle-mouse click, then this should work:

    function callback(event){
        if (!event.button === 1) return; // return if not middle button
        const ele = event.target.closest('div.sbqs_c');
        if (!ele) return; // guard incase it's wrong element because we are listening on `body` instead of `<ul>`
        const url = `https://www.youtube.com/results?search_query=${encodeURIComponent(ele.textContent)}`;
        window.open(url, '_blank');
    }
    
    document.body.addEventListener('auxclick', callback);
    

    you can add the 'auxclick' listener to the specific element (ul.sbsb_b) instead of the body, but you'll have to use a mutation observer for that, since the suggestions box does not load until the user interacts with the search box.