Bandwidth Unit Converter (bits → bytes)

Automatically converts Mbps, Gbps, Kbps into MB/s, GB/s, KB/s on webpages

La data de 18-08-2025. Vezi ultima versiune.

// ==UserScript==
// @name         Bandwidth Unit Converter (bits → bytes)
// @namespace    spotlightforbugs.scripts.bandwidth
// @version      1.0
// @description  Automatically converts Mbps, Gbps, Kbps into MB/s, GB/s, KB/s on webpages
// @author       SpotlightForBugs
// @license MIT
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function () {
  "use strict";

  // Conversion factors (bits → bytes)
  const conversions = {
    Kbps: { factor: 1 / 8, unit: "KB/s" },
    Mbps: { factor: 1 / 8, unit: "MB/s" },
    Gbps: { factor: 1 / 8, unit: "GB/s" },
    Tbps: { factor: 1 / 8, unit: "TB/s" },
  };

  // Regex to find numbers followed by units (e.g., "100 Mbps")
  const regex = new RegExp(
    "\\b(\\d+(?:\\.\\d+)?)\\s*(" + Object.keys(conversions).join("|") + ")\\b",
    "gi"
  );

  function convertText(text) {
    return text.replace(regex, (match, value, unit) => {
      const num = parseFloat(value);
      const { factor, unit: newUnit } = conversions[unit];
      const converted = (num * factor).toFixed(2);
      return `${match} (${converted} ${newUnit})`;
    });
  }

  function walk(node) {
    let child, next;

    switch (node.nodeType) {
      case 1: // Element
      case 9: // Document
      case 11: // Document fragment
        child = node.firstChild;
        while (child) {
          next = child.nextSibling;
          walk(child);
          child = next;
        }
        break;

      case 3: // Text node
        node.nodeValue = convertText(node.nodeValue);
        break;
    }
  }

  // Initial run
  walk(document.body);

  // Observe changes (for dynamic content)
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      mutation.addedNodes.forEach((node) => {
        walk(node);
      });
    });
  });

  observer.observe(document.body, {
    childList: true,
    subtree: true,
  });
})();
长期地址
遇到问题?请前往 GitHub 提 Issues。