无编码经验者求助:如何将特定Bookmarklet转为Greasemonkey脚本
嘿,别担心,我帮你把这个书签小工具转成Greasemonkey脚本,步骤超简单,哪怕没编码经验也能轻松搞定~
把Bookmarklet转成Greasemonkey脚本的完整指南
第一步:先搞懂Greasemonkey脚本的基础框架
Greasemonkey脚本需要一个特定的头部(元数据块),用来告诉浏览器脚本的运行规则,比如适用网站、功能描述这些。基础框架长这样:
// ==UserScript== // @name 你的脚本名称(比如:表格列计数工具) // @namespace http://your-namespace-here.com // @version 0.1 // @description 描述脚本功能(比如:统计网页表格的列数并显示) // @author 你的名字 // @match *://*/* // 可指定脚本运行的网站,比如只在某论坛就写https://example.com/* // @grant none // ==/UserScript== (function() { 'use strict'; // 核心代码放在这里 })();
第二步:移植你的Bookmarklet代码
你提供的代码有点截断了(最后是tab.rows[i].cel...),我先把已有的部分整合进去,你只需要把缺失的代码补全到对应位置就行。注意要去掉Bookmarklet开头的javascript:,然后把函数都放进Greasemonkey的自执行函数里:
// ==UserScript== // @name 表格列统计工具 // @namespace http://your-namespace.example // @version 0.1 // @description 统计网页表格的列数并做顶部提示 // @author MKen // @match *://*/* // @grant none // ==/UserScript== (function() { 'use strict'; // 从Bookmarklet移植的工具函数 function toArray(c) { var a, k; a = new Array; for (k = 0; k < c.length; ++k) a[k] = c[k]; return a; } function insAtTop(par, child) { if (par.childNodes.length) par.insertBefore(child, par.childNodes[0]); else par.appendChild(child); } function countCols(tab) { var nCols, i; nCols = 0; // 补全你截断的代码,这里假设是统计表格的最大列数 for (i = 0; i < tab.rows.length; ++i) if (tab.rows[i].cells.length > nCols) nCols = tab.rows[i].cells.length; return nCols; } // 脚本主逻辑:找到页面所有表格,统计列数并显示提示 const tables = document.querySelectorAll('table'); tables.forEach(table => { const colCount = countCols(table); // 创建提示元素 const notice = document.createElement('div'); notice.style.cssText = 'background: #ffeb3b; padding: 4px; font-size: 12px; margin-bottom: 8px;'; notice.textContent = `这个表格有 ${colCount} 列`; // 把提示放到表格上方 insAtTop(table.parentNode, notice); }); })();
第三步:怎么用这个脚本
- 先安装Greasemonkey(或者Tampermonkey,功能差不多)浏览器扩展
- 点击扩展图标,选择「新建用户脚本」
- 把上面的代码复制粘贴进去,替换掉默认的模板代码
- 保存脚本,刷新你要处理的网页,就能看到效果啦!
小提示
- 如果你的原始Bookmarklet有更多功能,记得把截断的代码补全到
countCols函数里,或者添加其他需要的函数 - 可以修改
@match字段来指定脚本只在特定网站运行,比如只在知乎就写@match https://www.zhihu.com/*,这样脚本不会在所有网页都运行,更高效
内容的提问来源于stack exchange,提问作者MKen
相关产品推荐
相关产品推荐

