tampermonkey 悬浮框显示状态面板

文章目录

    在写 tampermonkey 网页工具时,经常会用 console log 来输出状态日志,方便了解进度,或者调试。

    但是对于普通用户来说,这不太友好。还是能将进度信息显示在页面上比较直观。特别是对于用来自动挂学时的插件来说,没有这个状态显示,你很难知道插件是否因为页面改版导致挂了。。。

    所以参考了一个网上的脚本,写了一个测试程序。功能是,记录在当前页面停留了多长时间。

    以百度首页为例,这个悬浮框状态面板会显示在页面右下角,每秒更新。

    tampermonkey 显示状态面板

    这个 div 还是透明的,也不影响正常浏览。

    测试代码

    // ==UserScript==
    // @name         test_status_window
    // @namespace    http://tampermonkey.net/
    // @version      0.1
    // @description  try to take over the world!
    // @author       www.sunzhongwei.com
    // @match        https://www.tampermonkey.net/scripts.php
    // @match        https://www.baidu.com/*
    // @require      https://cdn.staticfile.org/jquery/1.9.1/jquery.min.js
    // @grant        none
    // ==/UserScript==
    
    (function() {
        'use strict';
    
        var end_hour = 0.1; // 几小时后停止
        var time_counter = 0;
        var end_second = end_hour * 60 * 60;
    
        $(
            '<div style="border: 2px dashed rgb(149, 252, 251); width: 330px; height: 330px; position: fixed; bottom: 0; right: 0; z-index: 99999; background-color: rgba(184, 247, 255, 0.3); overflow-x: auto; padding: 1em;">' +
              '<div>' +
                '<h2>状态面板</h2>' +
                '<div id="tm_status" style="margin-top: 1em;">' +
                '</div>' +
              '</div>' +
            '</div>'
        ).appendTo("body");
    
        setInterval(function() {
            time_counter += 1;
            showStatus(formatSecond(time_counter));
            if (time_counter > end_second) {
                finish();
            }
        }, 1000);
    
        function showStatus(status) {
            $("#tm_status").text(status);
        }
    
        function finish() {
            showStatus("结束! 已学习" + end_hour + "小时。");
        }
    
        function formatSecond(result) {
            const h = Math.floor((result / 3600) % 24);
            const m = Math.floor((result / 60) % 60);
            const s = Math.floor(result % 60);
            result = s + "秒";
            if (m > 0) {
                result = m + "分钟" + result;
            }
            if (h > 0) {
                result = h + "小时" + result;
            }
    
            return result;
        }
    })();
    

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式