zeddex zeddex - 16 days ago 6
Javascript Question

Tampermonkey - How to set text in the google search box?

How can i set some text in the google search box with tampermonkey?

I have tried the following but no text is set:

// ==UserScript==
// @name Google Search Test
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Testing selectors.
// @author You
// @match https://www.google.co.uk*
// @grant none
// ==/UserScript==

(function() {
'use strict';

var textinput = document.querySelector('input.gsfi[type=text]');
textinput.value = "Cats";
})();

Answer

Your selector is correct. You can simply check this by typing the code document.querySelector('input.gsfi[type=text]') into the JavaScript console. It should show the correct element.

The problem with the Google website is that the class of the input element is added after the Tampermonkey function is called (maybe trough some JavaScript).

So a workaround could be to check the input element after a short interval:

function test() {
    var textinput = document.querySelector('input.gsfi[type=text]');
    if (textinput!==null)
        textinput.value = "Cats";
    else
        console.log("textinput is null");
}

(function() {
    'use strict';
    setTimeout(test, 1000);
})();