前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用 TamperMonkey 增强生产力

使用 TamperMonkey 增强生产力

作者头像
Dylan Liu
发布2022-09-07 14:21:54
8640
发布2022-09-07 14:21:54
举报
文章被收录于专栏:dylanliudylanliudylanliu

简介

技术人员的日常积累其中的一部分就是总结不同的使用工具。现在各种软件都提供网站形式,在网站场景里,Javascript 是统治语言。TamperMonkey 提供了一种在网站上运行自己脚本的一种方式,应该成为我们工具箱里的一种常用工具。

安装

Tamper Monkey 是一个浏览器插件,可以使用在 Tamper 首页 https://www.tampermonkey.net/ 跳转到安装界面。

语法

语法文档: https://www.tampermonkey.net/documentation.php

新建脚本模版

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @icon         https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
// @match        http*://*/*
// @connect *
// @require https://code.jquery.com/jquery-2.1.4.min.js
// @run-at       document-idle
// @grant        unsafeWindow
// @grant        GM_xmlhttpRequest
// @grant        GM_openInTab
// @grant        GM_addStyle
// ==/UserScript==

(function() {
    'use strict';

    // Your code here...
})();

Meta 信息

@name, @namespace, @version, @description, @author, @icon 提供脚本的基本信息。

@match

@match 规定了脚本在什么网站上运行,http*://*/* 表明运行在所有的网站上,* 可用作通配符。 @match 的网站格式需要符合<url-pattern>的格式

<url-pattern> := <scheme>://<host><path>
<scheme> := '*' | 'http' | 'https' | 'file' | 'ftp' | 'urn'
<host> := '*' | '*.' <any char except '/' and '*'>+
<path> := '/' <any chars>

@connect

Tamper Monkey 支持 Ajax 调用函数 GM_xmlhttpRequest,@connect 指定了 ajax 可以调用的网址,* 表示可以调用任何网站,但会请求用户的确认,在不确定调用的网站是比较有用。 connect 规则:

  • domains like tampermonkey.net (this will also allow all sub-domains)
  • sub-domains i.e. safari.tampermonkey.net
  • self to whitelist the domain the script is currently running at
  • localhost to access the localhost
  • 1.2.3.4 to connect to an IP address

@require

加载脚本的依赖,像 jQuery 是比较常用的。

@run-at

定义脚本的运行时机,支持 document-start, document-body, document-end, document-idle(default), context-menu

@grant

@grant 用于给 脚本添加一下GM_* 函数, unsafeWindow 对象权限。 unsafeWindow 是当前页面的 JS window 对象,可以引用到所有的全局变量。 GM 函数列表

函数名

功能

GM_addStyle(css)

加载 css

GM_setValue(name, value)

保存一个值

GM_getValue(name, defaultValue)

获取key

GM_deleteValue(name)

删除一个值

GM_listValues()

列出所有的 keys

GM_log(message)

打印日志

GM_openInTab(url, options)

打开一个新tab

GM_xmlhttpRequest(details)

ajax 调用

GM_setClipboard(data, info)

保存data到剪贴板上,info 格式 "{ type: 'text', mimetype: 'text/plain'}"

GM_openInTab 参数

options 参数

  • active decides whether the new tab should be focused,
  • insert that inserts the new tab after the current one,
  • setParent makes the browser re-focus the current tab on close and
  • incognito makes the tab being opened inside a incognito mode/private mode window.
GM_xmlhttpRequest(details) 参数
  • method one of GET, HEAD, POST
  • url the destination URL
  • headers ie. user-agent, referer, ... (some special headers are not supported by Safari and Android browsers)
  • data some string to send via a POST request
  • cookie a cookie to be patched into the sent cookie set
  • binary send the data string in binary mode
  • nocache don't cache the resource
  • revalidate revalidate maybe cached content
  • timeout a timeout in ms
  • context a property which will be added to the response object
  • responseType one of arraybuffer, blob, json or stream
  • overrideMimeType a MIME type for the request
  • anonymous don't send cookies with the requests (please see the fetch notes)
  • fetch (beta) use a fetch instead of a xhr request (at Chrome this causes details.timeout and xhr.onprogress to not work and makes xhr.onreadystatechange receive only readyState 4 events)
  • user a user name for authentication
  • password a password
  • onabort callback to be executed if the request was aborted
  • onerror callback to be executed if the request ended up with an error
  • onloadstart callback to be executed on load start, provides access to the stream object if responseType is set to "stream"
  • onprogress callback to be executed if the request made some progress
  • onreadystatechange callback to be executed if the request's ready state changed
  • ontimeout callback to be executed if the request failed due to a timeout
  • onload callback to be executed if the request was loaded. It gets one argument with the following attributes:
    • finalUrl - the final URL after all redirects from where the data was loaded
    • readyState - the ready state
    • status - the request status
    • statusText - the request status text
    • responseHeaders - the request response headers
    • response - the response data as object if details.responseType was set
    • responseXML - the response data as XML document
    • responseText - the response data as plain string

Returns an object with the following property:

  • abort - function to be called to cancel this request

基本模版:

GM_xmlhttpRequest({
    method: "GET",
    url: "https://example.com",
    timeout: 5000,
    ontimeout: () => reject(' timeout'),
    onload: function (response) {
        if (response.status === 200) {
            // do sth
            resolve(response);
        }
        reject("Error occurred while retrieving data");
    },
    onerror: function (response) {
        reject("Error occurred while retrieving data");
    }
});
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-07-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简介
  • 安装
  • 语法
    • Meta 信息
      • @match
        • @connect
          • @require
            • @run-at
              • @grant
                • GM_openInTab 参数
                • GM_xmlhttpRequest(details) 参数
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档