如何编写Chrome Tampermonkey脚本实现自定义按钮触发目标按钮点击
Chrome Tampermonkey 自定义触发按钮脚本
以下代码可直接在Tampermonkey中使用,实现页面悬浮自定义按钮,点击后触发你指定的目标按钮点击操作,优化了原有参考代码的可用性,避免异常报错:
// ==UserScript== // @name 触发目标按钮快捷工具 // @namespace http://tampermonkey.net/ // @version 0.1 // @description 点击自定义按钮触发指定目标按钮点击 // @author You // @match *://*/* // @grant none // ==/UserScript== (function() { 'use strict'; // 目标按钮选择器 const TARGET_BTN_SELECTOR = "#root > div.sc-jtiXyc.jireel > div:nth-child(1) > div.product > div.container > div.create-listing > div.create-listing-btn-bar > button"; // 触发目标按钮点击 function triggerTargetBtn() { const targetBtn = document.querySelector(TARGET_BTN_SELECTOR); if (targetBtn) { targetBtn.click(); } else { alert("未找到目标按钮,请检查页面是否加载完成或选择器是否匹配"); } } // 创建自定义按钮 const customBtn = document.createElement("button"); customBtn.innerHTML = "Add to listing"; // 按钮样式 固定在右上角不遮挡页面内容 customBtn.style.cssText = ` position: fixed; top: 20px; right: 20px; z-index: 99999; padding: 8px 12px; background: #409eff; color: #fff; border: none; border-radius: 4px; cursor: pointer; box-shadow: 0 2px 4px rgba(0,0,0,0.2); `; document.body.appendChild(customBtn); // 绑定点击事件 customBtn.addEventListener('click', triggerTargetBtn); })();
使用步骤
- 打开Chrome浏览器的Tampermonkey扩展面板,选择「添加新脚本」
- 删除编辑器内默认生成的所有代码,粘贴上述代码
- 修改代码头部
@match后的匹配规则为你需要生效的网站域名,例如要在xxx.com下生效,可改为*://*.xxx.com/* - 按Ctrl+S保存脚本,刷新对应网站页面即可在右上角看到自定义按钮
内容的提问来源于stack exchange,提问作者Reza Sumairu
相关产品推荐
相关产品推荐

