zoukankan      html  css  js  c++  java
  • 油猴脚本折腾日记

    user script的编写并没有想象中那么复杂,基本上只要会点js就可以了,当然,为了方便,这里主要用的还是jquery。

    1. 文件头(Metadata)

    首先要声明一些东西。常见的annotation如下:

    // ==UserScript==
    // @name         脚本名称
    // @namespace    实际上用来指向一个页面当主页
    // @version      0.1
    // @description  描述
    // @author       作者
    // @match        *://www.baidu.com/*
    // @require      https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js
    // @grant        GM_getValue
    // @grant        GM_setValue
    // @grant        GM_addStyle
    // ==/UserScript==
    

    需要补充描述的有两个,一个是match,用来匹配网站url,可以写多个match;另一个是require,如果依赖外部库,可以这样插入对应的cdn url,如果没有依赖可以不写。至于grant,如果没有存储值的需求,可以不用setValue和getValue。

    2.  定位element

    为了方便从别的脚本里学了一种方法,先直接用$("selector1")定位,然后接一个.closest("select2")。当然,情况不复杂的时候可以不用closest

    2.1 创建和插入element

    也是用$,不过是$('<div class="A"></div>")这种形式。插入的话可以用jqueryObject的.append或者.prepend。

    2.2 字符串的获取与处理

    比如有一个input text或者textarea的jqueryObject叫textbox,获取值的话就用const text = textbox.val()。
    如果需要分割字符串,可以用split;比如按whitspace分隔,可以写成 text.split(/s+/) 。

    2.3 事件触发

    如果专门写个form再submit有点本末倒置,因为这样会导致页面重新载入。所以这里用的是 $.on("click",callback)。

    2.4 发送请求和数据处理

    一般用的是$.get或.post,回调函数function(data){}里面,如果返回的data是html,直接$($.parseHTML(data))就行,不用parse data的responseText(不知道是不是版本的问题,好像没有看到这个属性,建议根据实际情况做调整)。

    暂时涉及到的就这些。

    ref:

    https://www.tampermonkey.net/documentation.php

    https://api.jquery.com/category/manipulation/dom-insertion-inside/

    https://stackoverflow.com/questions/4088467/get-the-value-in-an-input-text-box

    https://stackoverflow.com/questions/11047670/creating-a-jquery-object-from-a-big-html-string

    https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/textarea

    https://stackoverflow.com/questions/48077912/javascript-how-to-strip-remove-a-char-from-string

    https://stackoverflow.com/questions/1418050/string-strip-for-javascript

  • 相关阅读:
    C语言第四章
    C第三章,指代数据
    DES+MD5加密
    时间选择器
    百度地图定位
    Httputils请求网络数据
    xStream解析xml文件
    pulltorefresh
    slidingmenu的应用
    Duutils创建数据库
  • 原文地址:https://www.cnblogs.com/pyzh/p/user-script-starter.html
Copyright © 2011-2022 走看看