开启辅助访问 切换到宽版

精易论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

用微信号发送消息登录论坛

新人指南 邀请好友注册 - 我关注人的新帖 教你赚取精币 - 每日签到


求职/招聘- 论坛接单- 开发者大厅

论坛版规 总版规 - 建议/投诉 - 应聘版主 - 精华帖总集 积分说明 - 禁言标准 - 有奖举报

查看: 1684|回复: 3
打印 上一主题 下一主题
收起左侧

[技术专题] A页面元素删除助手 油猴脚本 网页右上角 点击按钮 删除元素

[复制链接]
结帖率:100% (10/10)
跳转到指定楼层
楼主
发表于 2025-3-16 17:12:50 | 只看该作者 |只看大图 回帖奖励 |正序浏览 |阅读模式   山西省太原市
A页面元素删除助手 油猴脚本
自用不错,特分享绐有需要的人


复制代码 到油猴脚本中 保存
刷新网页即可
网页右上角 点击按钮 删除广告元素
下次打开网站 就不会有广告了




脚本.txt (10.37 KB, 下载次数: 5)


[JavaScript] 纯文本查看 复制代码
// ==UserScript==
// @name         A页面元素删除助手
// @Namespace    http://tampermonkey.net/
// @Version      0.1
// @description  悬浮一个按钮,点击后可手动选择元素并删除,记住删除元素下次不再显示,可查看删除记录
// @author       OK
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // 从 localStorage 中获取已删除元素的 XPath 列表
    const deletedElements = JSON.parse(localStorage.getItem('deletedElements')) || [];

    // 页面加载时删除之前记录的元素
    deletedElements.forEach(record => {
        const xpath = record.xpath; // 从记录对象中提取 XPath
        const elements = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
        for (let i = 0; i < elements.snapshotLength; i++) {
            const element = elements.snapshotItem(i);
            if (element) {
                element.parentNode.removeChild(element);
            }
        }
    });

    // 创建按钮容器
    const buttonContainer = document.createElement('div');
    buttonContainer.style.position = 'fixed';
    buttonContainer.style.top = '10px';
    buttonContainer.style.right = '-120px'; // 初始隐藏在页面右侧
    buttonContainer.style.zIndex = '9999';
    buttonContainer.style.transition = 'right 0.3s';
    // 设置按钮容器为 flex 布局,主轴方向为垂直方向
    buttonContainer.style.display = 'flex';
    buttonContainer.style.flexDirection = 'column';
    document.body.appendChild(buttonContainer);

    // 创建触发按钮
    const triggerButton = document.createElement('button');
    triggerButton.style.position = 'absolute';
    triggerButton.style.top = '0';
    triggerButton.style.right = '120px';
    triggerButton.textContent = '☰';
    triggerButton.addEventListener('click', function() {
        if (buttonContainer.style.right === '-120px') {
            buttonContainer.style.right = '10px';
        } else {
            buttonContainer.style.right = '-120px';
        }
    });
    buttonContainer.appendChild(triggerButton);

    // 创建悬浮按钮 - 删除元素
    const deleteButton = document.createElement('button');
    deleteButton.textContent = '删除元素';
    buttonContainer.appendChild(deleteButton);

    // 创建悬浮按钮 - 查看当前页面删除记录
    const viewRecordsButton = document.createElement('button');
    viewRecordsButton.textContent = '查看当前记录';
    buttonContainer.appendChild(viewRecordsButton);



    let isSelecting = false;

    // 定义被选元素的样式类
    const selectedElementClass = 'selected-element';
    const style = document.createElement('style');
    style.textContent = `.${selectedElementClass} { background-color: yellow !important; }`;
    document.head.appendChild(style);

    deleteButton.addEventListener('click', function() {
        console.log('删除元素按钮被点击,开始切换选择状态');
        isSelecting = !isSelecting;
        if (isSelecting) {
            deleteButton.textContent = '正在选择...';
            document.body.style.cursor = 'crosshair !important';
            deleteButton.style.display = 'none';

            // 鼠标移动到元素上时添加样式类
            document.addEventListener('mouseover', handleMouseOver);
            // 鼠标移开元素时移除样式类
            document.addEventListener('mouseout', handleMouseOut);
        } else {
            deleteButton.textContent = '删除元素';
            document.body.style.cursor = 'default';

            // 移除鼠标事件监听器
            document.removeEventListener('mouseover', handleMouseOver);
            document.removeEventListener('mouseout', handleMouseOut);
        }
    });

    function handleMouseOver(event) {
        if (isSelecting &&!buttonContainer.contains(event.target)) {
            event.target.classList.add(selectedElementClass);
        }
    }

    function handleMouseOut(event) {
        if (isSelecting &&!buttonContainer.contains(event.target)) {
            event.target.classList.remove(selectedElementClass);
        }
    }

    document.addEventListener('click', function(event) {
        if (isSelecting &&!buttonContainer.contains(event.target)) {
            event.preventDefault();
            let target = event.target;
            // 如果点击的是图片元素,获取其下方的元素
            if (target.tagName === 'IMG') {
                const rect = target.getBoundingClientRect();
                const x = rect.left + rect.width / 2;
                const y = rect.top + rect.height / 2;
                target = document.elementFromPoint(x, y);
            }
            const xpath = getXPath(target);
            const elements = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
            for (let i = 0; i < elements.snapshotLength; i++) {
                const element = elements.snapshotItem(i);
                if (element) {
                    element.parentNode.removeChild(element);
                    console.log('元素已删除');
                    // 创建提示元素
                    const notification = document.createElement('div');
                    notification.textContent = '元素已成功删除!';
                    notification.style.position = 'fixed';
                    notification.style.top = '20px';
                    notification.style.left = '50%';
                    notification.style.transform = 'translateX(-50%)';
                    notification.style.backgroundColor = 'green';
                    notification.style.color = 'white';
                    notification.style.padding = '10px';
                    notification.style.borderRadius = '5px';
                    notification.style.zIndex = '10001';
                    document.body.appendChild(notification);

                    // 一段时间后自动隐藏提示
                    setTimeout(() => {
                        document.body.removeChild(notification);
                    }, 3000);
                }
            }
            const currentUrl = window.location.href;
            // 检查记录是否已存在
            const existingRecord = deletedElements.find(record => record.xpath === xpath && record.url === currentUrl);
            if (!existingRecord) {
                // 修正此处代码,添加闭合括号
                deletedElements.push({ xpath, url: currentUrl });
                localStorage.setItem('deletedElements', JSON.stringify(deletedElements));
            }
            isSelecting = false;
            deleteButton.textContent = '删除元素';
            document.body.style.cursor = 'default';
            deleteButton.style.display = 'block';

            // 移除鼠标事件监听器
            document.removeEventListener('mouseover', handleMouseOver);
            document.removeEventListener('mouseout', handleMouseOut);
        }
    });

    viewRecordsButton.addEventListener('click', function() {
        const currentUrl = window.location.href;
        const currentPageRecords = deletedElements.filter(record => record.url === currentUrl);
        if (currentPageRecords.length === 0) {
            alert('当前页面暂无删除记录。');
        } else {
            showRecordsModal(currentPageRecords);
        }
    });

    viewAllRecordsButton.addEventListener('click', function() {
        if (deletedElements.length === 0) {
            alert('暂无任何网站的删除记录。');
        } else {
            showRecordsModal(deletedElements);
        }
    });

    function showRecordsModal(records) {
        const modal = document.createElement('div');
        modal.style.position = 'fixed';
        modal.style.top = '50%';
        modal.style.left = '50%';
        modal.style.transform = 'translate(-50%, -50%)';
        modal.style.backgroundColor = 'white';
        modal.style.padding = '20px';
        modal.style.border = '1px solid #ccc';
        modal.style.zIndex = '10000';
        // 设置模态框的最大高度和宽度,超出部分显示滚动条
        modal.style.maxHeight = '80vh';
        modal.style.maxWidth = '80vw';
        modal.style.overflow = 'auto';

        const closeButton = document.createElement('button');
        closeButton.textContent = '关闭';
        closeButton.addEventListener('click', function() {
            document.body.removeChild(modal);
        });
        modal.appendChild(closeButton);

        records.forEach((record, index) => {
            const recordDiv = document.createElement('div');

            const deleteRecordButton = document.createElement('button');
            deleteRecordButton.textContent = '删除';
            deleteRecordButton.addEventListener('click', function() {
                const indexToRemove = deletedElements.findIndex(r => r.xpath === record.xpath && r.url === record.url);
                if (indexToRemove!== -1) {
                    deletedElements.splice(indexToRemove, 1);
                    localStorage.setItem('deletedElements', JSON.stringify(deletedElements));
                    recordDiv.remove();
                }
            });
            recordDiv.appendChild(deleteRecordButton);

            const recordText = document.createElement('span');
            recordText.textContent = `${index + 1}. 网站: ${record.url}, XPath: ${record.xpath}`;
            recordDiv.appendChild(recordText);

            modal.appendChild(recordDiv);
        });

        document.body.appendChild(modal);
    }

    function getXPath(element) {
        if (element.id!=='') {
            return '//*[@id="' + element.id + '"]';
        }
        if (element === document.body) {
            return '/html/body';
        }
        let ix = 0;
        const siblings = element.parentNode.childNodes;
        for (let i = 0; i < siblings.length; i++) {
            const sibling = siblings;
            if (sibling === element) {
                return getXPath(element.parentNode) + '/' + element.tagName.toLowerCase() + '[' + (ix + 1) + ']';
            }
            if (sibling.nodeType === 1 && sibling.tagName === element.tagName) {
                ix++;
            }
        }
    }


})();




地板
发表于 2025-4-27 05:58:49 | 只看该作者   江西省宜春市
谢谢分享,学习一下
回复 支持 反对

使用道具 举报

签到天数: 3 天

板凳
发表于 2025-4-17 20:25:39 | 只看该作者   江苏省南京市
谢谢分享,学习一下
回复 支持 反对

使用道具 举报

沙发
发表于 2025-3-22 09:05:47 | 只看该作者   广东省东莞市
谢谢分享
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 致发广告者

发布主题 收藏帖子 返回列表

sitemap| 易语言源码| 易语言教程| 易语言论坛| 易语言模块| 手机版| 广告投放| 精易论坛
拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论,本站内容均为会员发表,并不代表精易立场!
论坛帖子内容仅用于技术交流学习和研究的目的,严禁用于非法目的,否则造成一切后果自负!如帖子内容侵害到你的权益,请联系我们!
防范网络诈骗,远离网络犯罪 违法和不良信息举报电话0663-3422125,QQ: 793400750,邮箱:[email protected]
网站简介:精易论坛成立于2009年,是一个程序设计学习交流技术论坛,隶属于揭阳市揭东区精易科技有限公司所有。
Powered by Discuz! X3.4 揭阳市揭东区精易科技有限公司 ( 粤ICP备12094385号-1) 粤公网安备 44522102000125 增值电信业务经营许可证 粤B2-20192173

快速回复 返回顶部 返回列表