Search code examples
javascriptinputplaceholdertampermonkeyuserscripts

YouTube Userscript (TamperMonkey) to change the placeholder in Search


I'm writing a theme in userscript for TamperMonkey to theme YouTube, the problem i'm having is with changing the font color & the content of the placeholder "Search" in the search field.

What's the best way to do this in userscript?


Solution

  • You can change the color of the placeholder with CSS. Important is, that the value from @grant is GM_addStyle and not none.

    Then you can add the styles like in the bottom example.

    With document.querySelector('input#search').placeholder = 'new placeholder text'; you can set a new text for the placeholder.

    @wOxxOm thx for the hint with the youtube event. yt-navigate-start event is to early, but with the yt-navigate-finish event and a 200ms delay it works.

    // ==UserScript==
    // @name         YouTube Search
    // @namespace     https://www.youtube.com
    // @include     https://www.youtube.com/*
    // @run-at document-end
    // @grant        GM_addStyle
    // ==/UserScript==
    
    GM_addStyle(`
    ::placeholder {
    color: red;
    opacity: 1; /* Firefox */
    }
    
    :-ms-input-placeholder { /* Internet Explorer 10-11 */
    color: red;
    }
    
    ::-ms-input-placeholder { /* Microsoft Edge */
    color: red;
    }
    `);
    
    (function() {
        'use strict';
    
        document.querySelector('input#search').placeholder = 'new placeholder text';
    
        document.addEventListener('yt-navigate-finish', () => {
            setTimeout(() => {
                document.querySelector('input#search').placeholder = 'new placeholder text';
            },200);
        });
    })();