移动端网络监测套件(极简版)

轻量级网络监测工具,优化性能与资源消耗

目前为 2025-03-05 提交的版本。查看 最新版本

// ==UserScript==
// @name         移动端网络监测套件(极简版)
// @namespace    http://tampermonkey.net/
// @version      4.1.0
// @description  轻量级网络监测工具,优化性能与资源消耗
// @license      MIT
// @match        http://*/*
// @match        https://*/*
// @run-at       document-start
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // 创建显示容器
    const container = (() => {
        const host = document.createElement('div');
        const shadow = host.attachShadow({ mode: 'closed' });
        document.documentElement.appendChild(host);
        const div = document.createElement('div');
        Object.assign(div.style, {
            position: 'fixed', right: '10px', bottom: '10px', zIndex: '999998',
            padding: '5px 10px', background: 'rgba(40,40,40,0.9)', color: '#f0f0f0',
            borderRadius: '8px', fontSize: '12px', fontFamily: 'system-ui, sans-serif'
        });
        shadow.appendChild(div);
        return div;
    })();

    let totalBytes = 0, latencyText = '延迟: ...';

    // 更新显示内容
    const updatePanel = () => {
        container.textContent = `流量: ${formatSize(totalBytes)} | ${latencyText}`;
    };

    // 格式化流量大小
    const formatSize = bytes => {
        if (bytes < 1024) return `${bytes} B`;
        if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
        return `${(bytes / 1048576).toFixed(2)} MB`;
    };

    // 监测资源流量
    new PerformanceObserver(list => {
        list.getEntries().forEach(entry => {
            const size = entry.transferSize || entry.decodedBodySize || 0;
            if (size > 0) totalBytes += size;
        });
        updatePanel();
    }).observe({ type: 'resource', buffered: true });

    // 测量网络延迟
    const measureLatency = () => {
        const start = performance.now();
        fetch(`${location.origin}/?t=${start}`, { method: 'HEAD', mode: 'no-cors', cache: 'no-store' })
            .then(() => {
                const latency = performance.now() - start;
                latencyText = `延迟: ${latency.toFixed(1)}ms`;
                container.style.color = latency < 100 ? '#4caf50' : latency < 300 ? '#ffb300' : latency < 500 ? '#ff9800' : '#f44336';
                updatePanel();
            })
            .catch(() => {
                latencyText = '延迟: 错误';
                container.style.color = '#f44336';
                updatePanel();
            });
    };

    // 定期更新延迟
    setInterval(measureLatency, 2000);

    // 初始化
    measureLatency();
    updatePanel();
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址