油猴脚本编程

脚本猫—定时脚本

2024-03-05  本文已影响0人  zip11

js定时脚本-脚本猫

写法
后台脚本必须使用Promise的形式,这样才能方便管理器进行管理,不遵循此规则的脚本可能会无法正常运行。除此之外,几乎与普通的油猴脚本没什么不同。因为后台脚本是在后台运行,所有针对window、dom的操作是无效的。另外为了满足后台脚本的一些交互,增强和扩展了一些API,具体可以看官方文档,教程后续也会继续讲解。


// ==UserScript==
// @name         后台脚本
// @namespace    wyz
// @version      1.0.0
// @author       wyz
// @background
// ==/UserScript==
return new Promise((resolve, reject) => {
  if (Math.round((Math.random() * 10) % 2)) {
    resolve("ok");// 执行成功
  } else {
    reject("error");// 执行失败,并返回错误原因
  }
});

每天运行一次的定时脚本


// ==UserScript==
// @name         每天运行一次的定时脚本
// @namespace    wyz
// @version      1.0.0
// @author       wyz
// @crontab      * * once * *
// ==/UserScript==
return new Promise((resolve, reject) => {
  if (Math.round((Math.random() * 10) % 2)) {
    resolve("ok");// 执行成功
  } else {
    reject("error");// 执行失败,并返回错误原因
  }
});

网页签到 例子


// ==UserScript==
// @name         pt_test_sign
// @namespace    pt_test_sign2
// @version      0.1.0
// @description  web sign
// @author       24-3-6
// @crontab      * * once * *
// @grant        GM_xmlhttpRequest
// @connect     test.club
// @grant        GM_notification
// ==/UserScript==
// 在此处键入代码……
return new Promise((resolve, reject) => {
    'use strict';
    // 定义目标URL
    var targetUrl = 'https://test.club/attendance.php'; 
    
    // 发送GET请求
    GM_xmlhttpRequest({
        method: 'GET',
        url: targetUrl,
        
        onload: function(response) {
            // 请求成功,显示返回的内容
            console.log('hdatmos 返回的内容:');
            console.log(response.responseText);
            GM_notification('hdatmos 签到 完成')
            resolve("pt_test_sign ok");
            // 执行成功
        },
        onerror: function(error) {
            // 请求失败,显示错误信息
            console.error('hdatmos 请求失败:', error);
            
            // 弹出提示框
            GM_notification('hdatmos 请求失败:', error)
            reject("pt_test_sign error"); 
            // 执行失败,并返回错误原因
        }
    });

});

上一篇 下一篇

猜你喜欢

热点阅读