zeddex
zeddex

Reputation: 1300

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";
})();

Upvotes: 1

Views: 1899

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

You can wait for the element to arrive. Just pass in a limit and the number of ms you will wait between each check.

function onArrival(selector, callback, interval, limit) {
  interval = interval || 1000; // Default wait time is 1 second.
  limit = limit || 10;         // Default number of attempts is 10.
  var el = document.querySelector(selector);
  if (el != null) {
    if (callback != null) {
      callback(el);
    }
  } else {
    if (limit > 0) {
      setTimeout(function() {
        onArrival(selector, callback, interval, limit - 1);
      }, interval);
    } else {
      console.log('Element not found!');
    }
  }
}

// Wait 3 seconds to load the input element.
setTimeout(function() {
  var label = document.createElement('label');
  label.innerHTML = 'Google Search: ';
  document.body.appendChild(label);
  
  var input = document.createElement('input');
  input.setAttribute('type', 'text');
  input.className = 'gsfi';
  document.body.appendChild(input);
}, 3000);

// Wait 5 times, 1 second at a time, for the input element to arrive.
onArrival('input[type="text"].gsfi', function(el) {
  el.value = 'Cats';
}, 1000, 5)

Upvotes: 3

gus27
gus27

Reputation: 2656

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);
})();

Upvotes: 0

Related Questions