n/haoyihaou/1panel · 2 个月前
注册 登录
n/haoyihao · 2 个月前 · 128 次浏览
u/1panel黄金

练手:写个 Chrome 插件去除论坛 “话题” 右侧边栏

1、先看效果

未去除前

未去除前

去除后

去除后

2、插件目录结构

一个最简单的 Chrome 插件只需要准备一个核心文件、一个配置文件、一个插件图标。在本地新建一个文件夹(比如叫 NodeLoc),并在里面创建以下内容:

NodeLoc/
├── manifest.json   # 插件配置文件
├── content.js      # 注入到网页中执行的逻辑脚本
└── 图标 icon512.png # 从 https://favicon.io/ 创建下载

2.1 图标创建

打开 https://favicon.io/ 选择 TEXT-->ICO 输入你喜欢的字母 点击下载 ,随便选一个png,重命名为 icon512.png 复制到 创建的 NodeLoc 文件夹下
图标创建

2.2 manifest.json —— 配置文件

告诉浏览器这个插件的名字、权限以及在访问什么网站时注入我们的脚本。

{
  "manifest_version": 3,
  "name": "NodeLoc 话题右侧边栏隐藏",
  "version": "1.0",
  "description": "自动隐藏 NodeLoc 右侧栏并让中间列表占满右侧空间",
  "icons": {
    "16": "icon512.png",
    "48": "icon512.png",
    "128": "icon512.png"
  },
  "content_scripts": [
    {
      "matches": ["*://*.nodeloc.com/*"],
      "js": ["content.js"],
      "run_at": "document_start"
    }
  ]
}

2.3 content.js —— 核心脚本逻辑

(function() {
    'use strict';

    // 用于缓存修改前的原始行内样式,避免粗暴 remove 破坏页面自带逻辑
    const originalStyles = new WeakMap();

    // 缓存并设置新样式
    function saveAndSetStyle(element, property, value) {
        if (!element) return;
        if (!originalStyles.has(element)) {
            originalStyles.set(element, {});
        }
        const styles = originalStyles.get(element);
        if (!(property in styles)) {
            styles[property] = element.style.getPropertyValue(property);
            const priority = element.style.getPropertyPriority(property);
            if (priority) {
                styles[property + '_priority'] = priority;
            }
        }
        element.style.setProperty(property, value, 'important');
    }

    // 完美还原样式
    function restoreElementStyles(element) {
        if (!element || !originalStyles.has(element)) return;
        const styles = originalStyles.get(element);
        
        for (const property in styles) {
            if (property.endsWith('_priority')) continue;
            const originalVal = styles[property];
            const priorityKey = property + '_priority';
            const originalPriority = styles[priorityKey] || '';

            if (originalVal === '') {
                element.style.removeProperty(property);
            } else {
                element.style.setProperty(property, originalVal, originalPriority);
            }
        }
        originalStyles.delete(element);
    }

    // 隐藏推广广告行
    function hidePromotionAds() {
        document.querySelectorAll('tr.promotion-feed-ad').forEach(tr => {
            if (!originalStyles.has(tr)) {
                originalStyles.set(tr, { display: tr.style.display });
            }
            tr.style.display = 'none';
        });
    }

    // 应用 /latest 专属布局
    function applyLayout() {
        const recentSidebar = document.querySelector('.meta-recent-posts');
        const adsWrapper = document.querySelector('.sidebar-ads-wrapper');
        if (recentSidebar) saveAndSetStyle(recentSidebar, 'display', 'none');
        if (adsWrapper) saveAndSetStyle(adsWrapper, 'display', 'none');

        const wrapper = document.getElementById('main-outlet-wrapper');
        if (wrapper) saveAndSetStyle(wrapper, 'grid-template-columns', 'auto 1fr');

        const mainOutlet = document.getElementById('main-outlet');
        if (mainOutlet) {
            saveAndSetStyle(mainOutlet, 'max-width', 'none');
            saveAndSetStyle(mainOutlet, 'width', 'calc(100% - 30px)');
            saveAndSetStyle(mainOutlet, 'margin', '0 auto');
            saveAndSetStyle(mainOutlet, 'padding-right', '15px');
        }
    }

    // 还原默认布局
    function restoreLayout() {
        restoreElementStyles(document.querySelector('.meta-recent-posts'));
        restoreElementStyles(document.querySelector('.sidebar-ads-wrapper'));
        restoreElementStyles(document.getElementById('main-outlet-wrapper'));
        restoreElementStyles(document.getElementById('main-outlet'));
    }

    // 核心路由分发器
    function handleRoute() {
        if (window.location.hostname === 'www.nodeloc.com') {
            if (window.location.pathname.startsWith('/latest')) {
                applyLayout();
                hidePromotionAds();
            } else {
                restoreLayout();
            }
        }
    }

    // 初次加载:利用 MutationObserver 抢先在关键元素诞生时执行
    const initObserver = new MutationObserver((mutations, observer) => {
        const wrapper = document.getElementById('main-outlet-wrapper');
        if (wrapper || document.body) {
            handleRoute();
            if (wrapper) observer.disconnect();
        }
    });

    // 安全加固:确保 document.documentElement 存在时再进行 observe
    if (document.documentElement) {
        initObserver.observe(document.documentElement, {
            childList: true,
            subtree: true
        });
    } else {
        document.addEventListener('DOMContentLoaded', () => {
            if (document.documentElement) {
                initObserver.observe(document.documentElement, {
                    childList: true,
                    subtree: true
                });
            }
        });
    }

    // 保底触发
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', handleRoute);
    } else {
        handleRoute();
    }

    // SPA 路由切换监控(针对 Discourse 的无刷新跳转)
    let lastPathname = window.location.pathname;
    setInterval(() => {
        if (window.location.pathname !== lastPathname) {
            lastPathname = window.location.pathname;
            handleRoute();
        }
    }, 200);

    // 动态加载广告监控(防止翻页或滚动时广告重新冒出来)
    const mutationObserver = new MutationObserver(() => {
        if (window.location.hostname === 'www.nodeloc.com' && window.location.pathname.startsWith('/latest')) {
            hidePromotionAds();
        }
    });

    if (document.body) {
        mutationObserver.observe(document.body, {
            childList: true,
            subtree: true
        });
    } else {
        document.addEventListener('DOMContentLoaded', () => {
            if (document.body) {
                mutationObserver.observe(document.body, {
                    childList: true,
                    subtree: true
                });
            }
        });
    }
})();

2.4 如何安装到你的 Chrome 浏览器中?

  1. 打开 Chrome 浏览器,在地址栏输入 chrome://extensions/ 并回车。
  2. 打开右上角的 “开发者模式” 开关。
  3. 点击左上角的 “加载已解压的扩展程序” 按钮。
  4. 选择你刚才创建的 NodeLoc 文件夹。
  5. 安装完成!打开 NodeLoc 论坛随便点进 话题 看看,是不是生效了?

3、其他

不想自己创建插件的,也可以使用 content.js中的代码在油猴脚本中使用

有兴趣的小伙伴可以自己动手试一试(嘿嘿,若脚本有bug就不修了,我比较懒 😆)

0
6
登录后参与讨论。
u/udc2b6nr 广告
QuicksilverVPN

快银 VPN,一键连接全球节点,线路稳定、延迟低。支持 Windows、macOS 等多平台,TUN 全局模式覆盖全部应用流量。无需复杂配置,下载即用。

umami.dnsl.top 了解更多

6 条回复

排序
  1. Arvin_Leung 🚗 3 YEARS 2 个月前

    不需要那么麻烦啊!

    直接去 偏好设置-界面,然后选择关闭就行了。记得保存

    3
  2. Struhaqi 黄金 2 个月前

    原来可以这样做 🤯

    0
  3. hynize 黄金 2 YEARS 2 个月前

    学习一下

    1
  4. loves 白银 2 个月前

    学习学习

    1
  5. yorushika 钻石 2 个月前

    :xhj26:

    1
  6. James 💯 传奇 MANAGER 2 个月前

    功能本身是有的;但是教程很好。如果有别的需求都可以根据教程自己DIY。这就是授人以渔。 大佬大义

    1