50行代码实现网页内容过滤(篡改猴脚本)

2024-07-16 | 128浏览 | 0评论 | 标签:篡改猴脚本

前言

有点标题党了,这是很早前自用的一段脚本,取名“页面净化”,基于浏览器扩展“篡改猴(Tampermonkey)”,用于屏蔽或弱化网页上不想看的烂七八糟的东西,包含广告、视频、声音、图片等等。

代码只包含了基础的框架,至于你想屏蔽什么网站,屏蔽什么内容,由你自己决定。只需要了解一点点的jQuery选择器用法,既可自由发挥。

使用方法

第一步:打开chrome浏览器,安装“篡改猴(Tampermonkey)”扩展(略);

第二步:【点此下载脚本

第三步:修改代码,添加想要屏蔽的网站或内容

1、// @match 表示作用于哪些网页,你可以换行在下面添加其它网站,比如知乎// @match https://*.zhihu.com/*

2、hideNodes表示需要屏蔽的元素,比如你想要屏蔽网页上的视频,一般视频标签为<video />,你可以这样写hideNodes: ['video']。只要jQuery选择器能抓取到的元素,就能生效。

3、opacityNodes表示需要弱化(降低透明度)的元素,使用方法同hideNodes

代码很简单,只要懂一点点基础的前端知识,就能看懂,我就不赘述了。

完整源码

// ==UserScript==
// @name         页面净化
// @description  隐藏任意网站的任意元素(图片/视频/文字/广告等),干干净净地冲浪。
// @version      1.0.0
// @match        https://*.zhihu.com/*
// @match        https://*.baidu.com/*
// @require      http://libs.baidu.com/jquery/2.0.0/jquery.min.js
// @namespace    https://greasyfork.org/users/978718
// @license MIT
// ==/UserScript==
this.$ = this.jQuery = jQuery.noConflict(true);
(function () {
  //公用方法
  const utils = {
    // 防抖
    throttle: function (func, wait) {
      let timeout;
      return function () {
        const context = this;
        const args = arguments;
        if (!timeout) {
          timeout = setTimeout(() => {
            timeout = null;
            func.apply(context, args)
          }, wait)
        }
      }
    }
  }
  //主要逻辑
  const view = {
    //直接隐藏的标签集合(需符合jQuery选择器写法)
    hideNodes: ['.c-container[mu*="xiaohongshu.com"]'],
    //降低透明度的标签集合(需符合jQuery选择器写法)
    opacityNodes: ['.QuestionHeader-title', '.QuestionHeader-content', '.AppHeader-inner'],
    // 入口
    init: function () {
      this.handleNodes();
      this.bindEvents();
    },
    // 处理
    handleNodes: function () {
      this.hideNodes.forEach(function (node) { $(node).css({ 'display': 'none' }); });
      this.opacityNodes.forEach(function (node) { $(node).css({ 'opacity': 0.01 }); });
    },
    // 绑定事件
    bindEvents: function () {
      $(window).on('scroll', utils.throttle(() => { this.handleNodes() }, 300))
    }
  }
  view.init();
})();

使用场景

待续...

(本篇完。有疑问欢迎留言探讨)

留言:

*

* (方便回复通知)

打赏
编辑代码 运行结果
退出