zeddex zeddex - 1 year ago 135
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 Source

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";
        console.log("textinput is null");

(function() {
    'use strict';
    setTimeout(test, 1000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download