javascript - Tampermonkey - 如何在谷歌搜索框中设置文本?

标签 javascript greasemonkey tampermonkey

如何使用 tampermonkey 在 google 搜索框中设置一些文本?

我已尝试以下操作,但未设置任何文本:

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

最佳答案

您可以等待元素到达。只需传递一个限制以及每次检查之间等待的毫秒数。

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)

关于javascript - Tampermonkey - 如何在谷歌搜索框中设置文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40723911/

相关文章:

javascript - 我可以更改另一个变量中的 javascript 变量吗?

javascript - 使用 jQuery 控制 HTML5 视频

javascript - 如何替换 URL 的一段并重新加载页面?

google-chrome - 使用 GM_xmlhttpRequest 在 Chrome 上发布数据?

iframe - 在域上运行 Tampermonkey 脚本,但不在 iframe 上运行

javascript - 如何将 activeadmin 查询字符串传递给batch_action?

javascript - jquery协助获取ms-vb2的子字符串

javascript - 如何将动态表单附加到表格末尾?

jquery - 如何使用greasemonkey脚本从互联网下载图像?

javascript - 使用用户脚本自动选中复选框?