[前端] 页面增强脚本

57 阅读3分钟

1、常见的元数据包含:

// ==Userscript==
// @name - 油猴脚本的名称
// @namespace 脚本的命名空间,用于确定脚本的唯一性
// @version 脚本的版本号,用于脚本的更新
// @description 脚本的描述信息
// @author 作者
// @require 定义脚本运行之前需要引入的外部 JS,比如:jQuery
// @match  使用通配符执行需要匹配运行的网站地址
// @exclude  排除匹配到的网站
// @grant  指定脚本运行所属的权限
// @connect  用于跨域访问时指定的目标网站域名
// @run-at  指定脚本的运行时机
// @updateUrl 脚本更新地址
// @downloadURL 脚本下载地址
// @icon 用于指定脚本的图标,可以设置为图片 URL 地址或 base64 的字符串
// ==/UserScript==
  1. 常见 API 油猴提供了很多强大的 API,用于操作缓存及窗口等,如果不需要使用这些 API,可以声明权限为 none,即:
@grant none

2-1 打印日志

用于在控制台中打印日志,便于调试

// 授权
@grant GM_log
// 在控制台打印日志
GM_log("Hello World");

2-2 缓存管理

包含对缓存的新增、获取、删除,在使用之前我们都需要使用关键字 @grant 进行授权

//授权
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_deleteValue
 
//设置缓存
GM_setValue("hello", true);
 
//获取缓存,默认值为true
GM_getValue("hello", true);
 
//删除缓存
GM_deleteValue("hello")

2-3 缓存监听

有时候,我们需要对缓存中的某个键的值进行监听,当发生变化时,调用一个方法事件

比如,这里新增了一个监听器,对键名为 hello 的值进行监听

// 授权
// @grant        GM_addValueChangeListener
// @grant        GM_removeValueChangeListener
 
// 添加一个监听器
const listener_id = GM_addValueChangeListener('hello', function(name, old_value, new_value, remote){
    if(hello == false){
        //具体的调用方法
        //....
    }
})
 
//监听监听器
GM_removeValueChangeListener(listener_id);

2-4 打开一个标签

格式:GM_openInTab(url, options)

该 API 可用于打开一个新的标签页面

其中,第一个参数用于指定新标签页面的 URL 地址,第二个参数用于指定页面展示方式及焦点停留页面

// 授权
// @grant        GM_openInTab
 
// 打开新页面
var onpenNewTap = function (){
    //打开百度页面
    //active:true,新标签页获取页面焦点
    //setParent :true:新标签页面关闭后,焦点重新回到源页面
    newTap = GM_openInTab("https://www.baidu.com",{ active: true, setParent :true});

2-5 跨域请求

在授予 GM_xmlhttpRequest 权限之后,就可以跨域发送请求了

PS:第一次跨域请求时,会弹出请求对话框,需要选中允许,才能正常进行跨域请求

// 授权
// @grant        GM_xmlhttpRequest
 
GM_xmlhttpRequest({
    url:"http://www.httpbin.org/post",
    method:'POST',
    headers: {
    "content-type": "application/json"
      },
    data:"",
    onerror:function(res){
        console.log(res);
    },
    onload:function(res){
        console.log(res);
    }
});

从零快速编写一个油猴脚本

3、模拟事件 在编写页面增强脚本的时候我们可能需要触发一些事件,如input, click, move等等

使用Event 事件对象 可以完成自定触发事件。

例如,模拟在某个inputA上输入, 然后触发对应元素的inputB

/**
 * 模拟在filter_input上输入
 * @param targetNode 需要触发事件的dom元素
 */
function simulateInput(targetNode) {
    function triggerInput(targetNode, eventType) {
        let clickEvent = new Event(eventType, { "bubbles": true, "cancelable": true }); 
        // 新建事件 eventType => 事件类型    { "bubbles": 事件是否冒泡, "cancelable": 事件是否可以取消 }  
        targetNode.dispatchEvent(clickEvent); // 触发对应事件
    }

    ['input'].forEach(function (eventType) {
        triggerInput(targetNode, eventType);
    });
}