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

文章讲述了如何使用tampermonkey等用户脚本工具,配合JS脚本来自动化替换Grafana监控面板中的错误码,通过定时弹窗和按钮交互设计实现更便捷的维护。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景:

使用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
// @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
// @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
// @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", ()=>{
        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;
                }
            }

        })
    });
})();

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值