如何使用 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/