如何编写Chrome+Tampermonkey脚本给指定CSS路径文本框输入内容?
Hey Mariah! Let's tackle your questions one by one—this is pretty straightforward once you know the basics.
First off, you need two core steps: locate the text box element, then populate it with your text. Here's how to do it in vanilla JavaScript (which works for browsers and Tampermonkey):
- Locate the element: Use methods like
document.querySelector()(for CSS selectors) ordocument.getElementById()(if the box has an ID). For example, if your text box has a classsearch-input, you'd usedocument.querySelector('.search-input'). - Set the text: Once you've got the element reference, you can directly set its value with
element.value = "Your desired string". - Trigger input events (critical for some sites): Many websites listen for
inputevents to enable buttons, validate text, or update UI. To mimic real user input, dispatch this event after setting the value:
Theconst textBox = document.querySelector('your-selector-here'); textBox.value = "Hello World!"; textBox.dispatchEvent(new Event('input', { bubbles: true }));bubbles: trueflag ensures the event propagates up the DOM, just like a real user's input would.
Since you already know how to handle the Apply button, let's focus on building a reliable script that targets your specific text box (input[type='input']). Here's a complete, commented script you can drop into Tampermonkey:
// ==UserScript== // @name Auto-Fill & Apply // @namespace http://tampermonkey.net/ // @version 0.1 // @description Automatically fills target text box and clicks Apply button // @author Your Name // @match https://your-target-site.com/* // Replace this with your actual site URL! // @grant none // ==/UserScript== (function() { 'use strict'; // Wait a second for dynamic content to load (adjust timeout if needed) setTimeout(() => { // Step 1: Grab the target text box const textBox = document.querySelector('input[type="input"]'); if (!textBox) { console.log("Oops, couldn't find the text box!"); return; } // Step 2: Input your text and trigger the input event textBox.value = "Your custom text here"; textBox.dispatchEvent(new Event('input', { bubbles: true, cancelable: true })); // Step 3: Click the Apply button (use your known selector/method here) // Example: If the button has an ID 'apply-btn' const applyBtn = document.querySelector('#apply-btn'); // Alternative: If the button has text "Apply" // const applyBtn = Array.from(document.querySelectorAll('button')).find(btn => btn.textContent.trim() === 'Apply'); if (applyBtn) { applyBtn.click(); console.log("Success! Text entered and Apply clicked."); } else { console.log("Apply button not found—double-check your selector!"); } }, 1000); // Adjust this number if elements load slower (e.g., 2000 for 2 seconds) })();
Pro Tip for Dynamic Sites:
If the text box or button loads after the initial page load (like via AJAX), a setTimeout might be hit-or-miss. For better reliability, use a Mutation Observer to wait until the elements exist:
// ==UserScript== // @name Auto-Fill & Apply (Reliable Version) // @namespace http://tampermonkey.net/ // @version 0.1 // @description Automatically fills target text box and clicks Apply button (waits for elements) // @author Your Name // @match https://your-target-site.com/* // @grant none // ==/UserScript== (function() { 'use strict'; function performAction() { const textBox = document.querySelector('input[type="input"]'); const applyBtn = document.querySelector('#apply-btn'); // Use your button selector if (textBox && applyBtn) { textBox.value = "Your custom text here"; textBox.dispatchEvent(new Event('input', { bubbles: true })); applyBtn.click(); console.log("Action completed successfully!"); observer.disconnect(); // Stop observing once done } } // Set up observer to watch for DOM changes const observer = new MutationObserver((mutations) => { mutations.forEach(performAction); }); observer.observe(document.body, { childList: true, subtree: true }); performAction(); // Check immediately in case elements are already loaded })();
Just remember to replace the @match URL with the actual site you're working on, and adjust the Apply button selector to match what you already know about the button's implementation.
内容的提问来源于stack exchange,提问作者Mariah

