You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决Tampermonkey/Greasemonkey中addEventListener失效及自动点击按钮问题

5位密码自动登录脚本(适配Greasemonkey/Tampermonkey)

问题背景

需求是在各网站登录页输入5位密码后,0.1秒自动点击登录按钮。原代码在浏览器控制台可正常运行,但在油猴插件中失效报错,且确认目标元素存在,需要实现脚本永久生效。

修正后的脚本

// ==UserScript==
// @name         5位密码自动点击登录
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  输入5位密码后0.1秒自动触发登录按钮
// @author       自定义名称
// @match        *://*/*login*
// @match        *://*/*signin*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // 等待目标元素加载完成
    function waitForElement(selector, callback) {
        const element = document.querySelector(selector);
        if (element) {
            callback(element);
            return;
        }
        // 监听DOM变化,直到元素出现
        const observer = new MutationObserver((mutations) => {
            mutations.forEach(() => {
                const targetElement = document.querySelector(selector);
                if (targetElement) {
                    observer.disconnect();
                    callback(targetElement);
                }
            });
        });
        observer.observe(document.body, { childList: true, subtree: true });
    }

    // 监听密码框输入事件
    waitForElement('input[type="password"]', (passwordBox) => {
        passwordBox.addEventListener('input', function() {
            const inputContent = this.value.trim();
            if (inputContent.length === 5) {
                setTimeout(() => {
                    // 优先匹配submit类型的登录按钮
                    let loginButton = document.querySelector('button[type="submit"], input[type="submit"]');
                    // 如果没找到,匹配包含登录/Login文本的按钮
                    if (!loginButton) {
                        loginButton = Array.from(document.querySelectorAll('button, input[type="button"]')).find(btn => {
                            const btnText = btn.textContent.trim().toLowerCase();
                            return btnText.includes('登录') || btnText.includes('login');
                        });
                    }
                    // 找到按钮则触发点击
                    if (loginButton) loginButton.click();
                }, 100);
            }
        });
    });
})();

关键修改说明

  • 页面匹配规则:通过@match匹配所有包含login或signin的页面,覆盖绝大多数登录场景
  • 元素加载等待:新增waitForElement函数,用MutationObserver监听DOM变化,解决脚本执行时目标元素还未渲染的问题(原脚本直接获取元素可能因为DOM未加载完成导致失败)
  • 多网站适配:密码框用通用选择器input[type="password"],登录按钮优先匹配submit类型,再通过文本内容匹配,兼容不同网站的按钮结构
  • 沙箱兼容:设置@grant none让脚本运行在页面上下文,避免油猴沙箱导致的元素获取权限问题
  • 代码规范:用立即执行函数包裹代码,避免污染全局变量,符合油猴脚本开发规范

内容的提问来源于stack exchange,提问作者Mjniyazi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 10:20:27