Bookmarklet

Bookmarklet 是什么

A bookmarklet is a bookmark stored in a web browser that contains JavaScript commands that add new features to the browser. They are stored as the URL of a bookmark in a web browser or as a hyperlink on a web page. Bookmarklets are usually small snippets of JavaScript executed when user clicks on them. When clicked, bookmarklets can perform a wide variety of operations, such as running a search query from selected text or extracting data from a table.

Bookmarklet 可以做什么

  • 浏览器的自动填充功能在部分网站的登录页面不会生效, 点击输入框也不会显示下拉历史记录, 可以使用bookmarklet实现自动输入填充信息登录
1
javascript:(function(){document.querySelector('#uCode').value='username';document.querySelector('#pW').value='password';document.querySelector('#login_btn%20%3E%20button.login').click();})();
  • 写文章时候, 经常会放上一些摘抄的原网址的标题和链接, 使用下面的bookmarklet可以快速获取文章标题和链接
1
alert(`[${document.title}](${document.URL})`)
  • 上一条改良一下, 直接将markdown格式的链接复制到剪贴板, 免去手动复制
1
navigator.clipboard.writeText(`[${document.title}](${document.URL})`)
  • 再优化一点, 复制成功之后加一个效果(网页标题短暂跳成"Copied!“之后又恢复)
1
navigator.clipboard.writeText(`[${document.title}](${document.URL})`);var tt = document.title;document.title="Copied!";setTimeout(()=>{document.title=tt}, 1e3)

如何编写 bookmarklet

你只需要编写常规的JavaScript, 网络上有很多在线转换工具, 帮助将常规的js代码生成bookmarklet, 比如:

Bookmarklet Maker

引用

Bookmarklet - Wikipedia

阮一峰的 Bookmarklet编写指南