简单写个JS插件替换网页上的文本

news2025/6/24 6:38:18

背景:

使用Grafana监控面板,随着项目迭代,页面上几百个图表了,相当一部分和错误码有关,逐个图表单替换维护过于繁琐,于是尝试一键替换grafana面板上的错误码(也就替换网页上特定的文本元素),原理上应该很简单,浏览器翻译插件都做到了。

咱们简单实现,思路是执行一个JS脚本,找到要替换的文本,完成替换工作。

*monkey 类的脚本插件(比如 tampermonkey )可以帮忙根据网站地址执行脚本。ScriptCat 是 *monkey类插件中UI比较美观的。下面以此为例,添加Script.
在这里插入图片描述

如下,简单写好了脚本:

// ==UserScript==
// @name         CodeMapper
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        http://你希望脚本起作用的网站/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=shopee.io
// @grant        none
// ==/UserScript==

(function() {
    sleep(5000);
    var codeEnum = {
    "1005110001": "codec param error",
    "1005310001": "download url error",
    };

    var labels = document.querySelectorAll("div.css-w166kv-LegendLabel-LegendClickable,div.css-1ns0gep-LegendLabel-LegendClickabel");
    labels.forEach((ele, _, __)=> {
        // console.log(ele.innerHTML)
        // ele.innerHTML = "******"
        for(var code in codeEnum) {
            var msg = codeEnum[code];
            // ele.innerHTML = "*********"
            if(true || ele.innerHTML.indexOf(code)>=0) {
                var target =  String(ele.innerHTML).replace(code, "["+msg+"]"+"("+code+")");
                console.log(target);
                ele.innerHTML = target;
            }
        }

    })
})();

发现 *monkey类工具,不能保证我网页异步加载完成了再执行脚本,也不支持手动触发脚本的执行。

不过也不难解决,如下图,可以通过,定时弹窗 confirm来控制脚本执行。

// ==UserScript==
// @name         CodeMapper
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match       http://你希望脚本起作用的网站/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=shopee.io
// @grant        none
// ==/UserScript==

(function () {
    var inter_ = setInterval(() => {
        var res__ = confirm("run stript?")
        if (!res__) {
            // 时机未到
            return;
        }
         clearInterval(inter_);

        var codeEnum = {
            "1005110001": "codec param error",
            "1005310001": "download url error",
        };

        var labels = document.querySelectorAll("div.css-w166kv-LegendLabel-LegendClickable,div.css-1ns0gep-LegendLabel-LegendClickabel");
        labels.forEach((ele, _, __) => {
            // console.log(ele.innerHTML)
            // ele.innerHTML = "******"
            for (var code in codeEnum) {
                var msg = codeEnum[code];
                // ele.innerHTML = "*********"
                if (true || ele.innerHTML.indexOf(code) >= 0) {
                    var target = String(ele.innerHTML).replace(code, "[" + msg + "]" + "(" + code + ")");
                    console.log(target);
                    ele.innerHTML = target;
                }
            }

        })
    }, 5000)

})();

还是不太好用,让网页上显示一个小按钮,点击后执行,才是比较好的交互方式。
前端不是很熟悉,让GPT来帮忙吧。

How to inject a button into a web page by JavaScript, require the button to hover in the top right corner of the web page, require the button to be a white button with rounded corners with a shadow, the button to have an image icon, when clip that button, show hello world confirm dialog

o inject a button into a web page using JavaScript with the specified requirements of having a button hover in the top right corner, being a white button with rounded corners and a shadow, and having an image icon, along with the functionality to show a confirm dialog when clicked, you can follow these steps:

Create the button element using the createElement method and set its properties such as id and class.

Style the button using CSS to achieve the desired appearance by setting its background color, border radius, box shadow, position, and other relevant styles.

Add the image icon to the button element either by setting its innerHTML or creating an img element as a child of the button.

Attach an event listener to the button to listen for the click event. Inside the event listener, show the confirm dialog using the confirm function.

Here’s an example code snippet that demonstrates injecting a button with the specified requirements:

// Step 1: Create the button element
var button = document.createElement('button');
button.id = 'my-button';
button.className = 'hover-button';

// Step 2: Style the button
button.style.backgroundColor = 'white';
button.style.borderRadius = '10px';
button.style.boxShadow = '0 2px 5px rgba(0, 0, 0, 0.3)';
button.style.position = 'fixed';
button.style.top = '20px';
button.style.right = '20px';

// Step 3: Add the image icon to the button
var iconImg = document.createElement('img');
iconImg.src = 'path/to/icon.png'; // Replace with the path to your image icon
iconImg.alt = 'Icon';
button.appendChild(iconImg);

// Step 4: Attach an event listener to the button
button.addEventListener('click', function() {
  var confirmed = confirm('Hello World!');
  if (confirmed) {
    // Add your desired functionality here
    console.log('Confirmed');
  }
});

// Step 5: Attach the button to the document or container
document.body.appendChild(button);
In this example, the button is given the class hover-button in addition to the specified styles. You can define the hover-button class in your CSS file or inline using the style attribute to further customize the button’s appearance.

Make sure to replace ‘path/to/icon.png’ with the actual path to your desired image icon.

When the button is clicked, a confirm dialog with the message “Hello World!” will be shown. If the user confirms the dialog, the code inside the if statement will execute (in this case, logging “Confirmed” to the console). You can modify the code inside the if statement to perform any desired functionality.

Adjust the positioning, styling properties, and confirm dialog message as needed to fit your requirements.

好了结合他的回答,改一下上面的代码:

// ==UserScript==
// @name         CodeMapper
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        http://你希望脚本起作用的网站/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=shopee.io
// @grant        none
// ==/UserScript==

function button_do(icon, f) {
    // Step 1: Create the button element
    var button = document.createElement('button');
    button.id = 'my-button';
    button.className = 'hover-button';

    // Step 2: Style the button
    button.style.backgroundColor = 'white';
    button.style.borderRadius = '10px';
    button.style.boxShadow = '0 2px 5px rgba(0, 0, 0, 0.3)';
    button.style.position = 'fixed';
    button.style.top = '20px';
    button.style.right = '20px';

    // Step 3: Add the image icon to the button
    var iconImg = document.createElement('img');
    iconImg.src = icon; // Replace with the path to your image icon
    iconImg.alt = 'Icon';
    button.appendChild(iconImg);

    // Step 4: Attach an event listener to the button
    button.addEventListener('click', function() {
        f();
    });

    // Step 5: Attach the button to the document or container
    document.body.appendChild(button);
}

(function () {
    button_do("https://www.google.com/s2/favicons?sz=64&domain=shopee.io", ()=>{
        var codeEnum = {
            "1005110001": "codec param error",
            "1005310001": "download url error",
        };

        var labels = document.querySelectorAll("div.css-w166kv-LegendLabel-LegendClickable,div.css-1ns0gep-LegendLabel-LegendClickabel");
        labels.forEach((ele, _, __) => {
            // console.log(ele.innerHTML)
            // ele.innerHTML = "******"
            for (var code in codeEnum) {
                var msg = codeEnum[code];
                // ele.innerHTML = "*********"
                if (true || ele.innerHTML.indexOf(code) >= 0) {
                    var target = String(ele.innerHTML).replace(code, "[" + msg + "]" + "(" + code + ")");
                    console.log(target);
                    ele.innerHTML = target;
                }
            }

        })
    });
})();

效果如下
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1086147.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

禅道如何编辑项目模块

禅道是一个用于项目管理和软件开发的开源工具,它的主要作用包括: 1. 项目管理:禅道可以帮助项目团队进行任务分配、进度跟踪、沟通协作、测试管理等方面的工作,以确保项目能够按时完成。 2. 缺陷追踪:禅道可以记录和…

钉钉数字校园小程序开发:开启智慧教育新时代

随着信息技术的快速发展和校园管理的日益复杂化,数字校园已成为现代教育的重要趋势。钉钉数字校园小程序作为一种创新应用,以其专业性、思考深度和逻辑性,为学校提供了全新的管理、教学和沟方式。本文从需求分析、技术实现和应用思考三个方面…

JAVA学习第一天,java的运行方式

对未来很迷茫,不知道以后能出去干什么,好像掌握的东西很少,从今天开始学习学习java吧,让自己充实起来,记录一下。 jav…

QT快速下载

官网下载安装包后,打开命令行CMD,将qt安装包拖入cmd中 添加–mirror https://mirrors.tuna.tsinghua.edu.cn/qt 回车 按安装步骤安装即可

大模型评测指标与方法

中文大模型评测和英文评测方法是不一致的,原因: 第一、数据集的差异性。中文和英文的文本数据集在种类、规模、质量等方面存在很大的差异,需要针对中文特点开发相应的数据集,以确保评测结果的准确性和公正性。 第二、语言结构和…

计算机毕业设计选什么题目好?springboot 航司互售系统

✍✍计算机编程指导师 ⭐⭐个人介绍:自己非常喜欢研究技术问题!专业做Java、Python、微信小程序、安卓、大数据、爬虫、Golang、大屏等实战项目。 ⛽⛽实战项目:有源码或者技术上的问题欢迎在评论区一起讨论交流! ⚡⚡ Java实战 |…

M-LVDS收发器MS2111可pin对pin兼容SN65MLVD206

MS2111 是多点低压差分(M-LVDS)线路驱动器和接收器,经过优化可在高达 200 Mbps 的信令速率下运行。可pin对pin兼容SN65MLVD206。所有部件均符合 M-LVDS 标准 TIA / EIA-899。该驱动器输出已设计为支持负载低至 30Ω 的多点总线。 MS2111 的接收器属于 Type-2, 它们可…

一文拿捏对象内存布局及JMM(JAVA内存模型)

1 JMM(Java Memory Model) 1 概述 Java内存模型(Java Memory Model简称JMM)是一种抽象的概念,并不真实存在,它描述的一组规则或者规范。通过这些规则、规范定义了程序中各个变量的访问方式。jvm运行的程序的实体是线程,而每个线程运行时&am…

网页视频F12倍速看

首先在看视频的网页,点击F12,出现下方页面,其他页面不用管 方式一: document.querySelector("video").playbackRate"16"; 16指的是倍速,可随意修改 方式二: document.querySelecto…

203、RabbitMQ 之 使用 direct 类型的 Exchange 实现 消息路由 (RoutingKey)

目录 ★ 使用direct实现消息路由代码演示这个情况二ConstantUtil 常量工具类ConnectionUtil 连接RabbitMQ的工具类Publisher 消息生产者测试消息生产者 Consumer01 消息消费者01测试消费者结果: Consumer02 消息消费者02测试消费者结果: 完整代码&#x…

Centos8 openjdk升级

1、卸载旧版本 sudo dnf remove java-1.8.0-openjdk 2、搜索新版本 yum search java-11-openjdk3、安装新版本 dnf install java-11-openjdk.x86_644、验证新版本 java -version

Python+”高光谱遥感数据处理与机器学习深度应用丨高光谱数据预处理-机器学习-深度学习-图像分类-参数回归

涵盖高光谱遥感数据处理的基础、python开发基础、机器学习和应用实践。重点解释高光谱数据处理所涉及的基本概念和理论,旨在帮助学员深入理解科学原理。结合Python编程工具,专注于解决高光谱数据读取、数据预处理、高光谱数据机器学习等技术难题&#xf…

《UnityShader入门精要》学习2

UnityShader 基础 UnityShader 概述 一对好兄弟:材质和UnityShader 总体来说,在Unity中我们需要配合使用材质(Material)和Unity Shader才能达到需要的效果。一个最常见的流程是: (1)创建一个…

第 5 章 数组和广义表(稀疏矩阵的三元组顺序表存储实现)

1. 背景说明 为了节省存储空间&#xff0c;可以对这类矩阵进行压缩存储。所谓压缩存储是指&#xff1a;为多个值相同的元只分配一个存储空间&#xff0c;对零元不分配空间。 2. 示例代码 1)status.h /* DataStructure 预定义常量和类型头文件 */ #include <string.h>#i…

Adobe Premiere Elements 2024:轻松创建精彩视频的简化版专业工具

随着视频内容的日益流行和人们对高质量多媒体内容的需求不断增长&#xff0c;Adobe Premiere Elements 2024 成为了许多非专业视频编辑者首选的工具。这款软件究竟有何特别之处&#xff1f;本文将详细介绍 Adobe Premiere Elements 2024&#xff0c;并为您揭示它的简化版专业功…

Java集合(四) --- Map

好潦草的一篇文章&#xff0c;不想学习想摆烂了又 &#xff0c;凑合看 文章目录 一、Map的实现类的结构二、Map结构的理解三、HashMap的底层实现原理? 以jdk7的说明:四、Map中定义的方法五、总结&#xff1a;常用方法六、代码 提示&#xff1a;以下是本篇文章正文内容&#xf…

企业活动目录管理利弊

凡事都有利和弊&#xff0c;那么如何解决企业活动目录管理中的各种弊端呢&#xff1f; 首先Windows环境是目前企业使用率最高的网络环境&#xff0c;作为windows最核心的组件&#xff0c;活动目录&#xff08;AD域&#xff09;自然被很多企业使用&#xff0c;其主要作用就是更…

goland 旧版本使用1.19环境

C:\Go\src\runtime\internal\sys\zversion.go // Code generated by go tool dist; DO NOT EDIT.package sysconst StackGuardMultiplierDefault 1const TheVersion go1.19引入其他包的标识符 package mainimport ("fmt""gotest/test")func main() {f…

扫描器(xray和bp联动)

文章目录 分类主动扫描和被动扫描bp与xray联动 分类 扫描器分为对web的扫描器和对主机的扫描器 主动扫描和被动扫描 主动扫描&#xff1a; 输入某个URL&#xff0c;然后由扫描器中的爬虫模块爬取所有链接&#xff0c;对GET、POST等请求进行参数变形和污染&#xff0c;进行重放测…