分享一下关键词屏蔽脚本

guyuege 2026-06-18 01:21 1

油猴添加新脚本,粘贴保存


// ==UserScript==
// @name NodeSeek 屏蔽关键词
// @namespace http://tampermonkey.net/
// @version 5.8
// @description 按关键词屏蔽帖子(默认显示、仅隐藏命中帖);关键词内存缓存 + 帖子插入即处理,性能与首屏体验优先
// @match https://www.nodeseek.com/*
// @grant none
// @run-at document-start
// ==/UserScript==

(function () {
'use strict';

const STORAGE_KEY = 'nodeseek_block_keywords';
const BLOCK_CLASS = 'nsk-blocked';

// ✅ 默认显示,仅命中关键词的帖子隐藏(不再全隐藏,正常帖子跟随页面原生速度出现)
const style = document.createElement('style');
style.textContent = `
.post-list-item.${BLOCK_CLASS} {
display: none !important;
}

/* 屏蔽按钮 */
#keyword-block-btn {
position: fixed;
top: 12px; /* 兜底值,实际由 JS 对齐到导航栏中线 */
right: 12px;
z-index: 10000;
height: 32px;
padding: 0 14px;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 13px;
line-height: 1;
color: #444;
background: #f0f0f0;
border: 1px solid #ddd;
border-radius: 6px;
cursor: pointer;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
transition: background 0.15s ease, box-shadow 0.15s ease;
}
#keyword-block-btn:hover {
background: #e6e6e6;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
}
#keyword-block-btn:active {
background: #dcdcdc;
}

/* ---- 内联模式:嵌入网站顶栏图标条,跟随原生图标配色 ---- */
#keyword-block-btn.nsk-inline {
position: static;
top: auto;
right: auto;
height: auto;
padding: 8px;
margin: 0;
color: inherit; /* 跟随顶栏图标颜色,自动适配深/浅色 */
background: transparent;
border: none;
border-radius: 6px;
box-shadow: none;
}
#keyword-block-btn.nsk-inline:hover {
background: rgba(128, 128, 128, 0.18);
box-shadow: none;
}
#keyword-block-btn.nsk-inline:active {
background: rgba(128, 128, 128, 0.28);
}
#keyword-block-btn.nsk-inline svg {
display: block;
}

/* ---- 悬浮图标模式(电脑端):保持 fixed 定位,透明背景、图标风格 ---- */
#keyword-block-btn.nsk-icon {
height: auto;
padding: 6px;
color: #555;
background: transparent;
border: none;
box-shadow: none;
}
#keyword-block-btn.nsk-icon:hover {
background: rgba(128, 128, 128, 0.15);
box-shadow: none;
}
#keyword-block-btn.nsk-icon:active {
background: rgba(128, 128, 128, 0.25);
}
#keyword-block-btn.nsk-icon.nsk-icon-dark {
color: #ccc;
}
#keyword-block-btn.nsk-icon svg {
display: block;
}

/* 设置面板 */
#keyword-block-panel {
position: fixed;
top: 52px;
right: 12px;
z-index: 10000;
min-width: 240px;
padding: 14px;
background: #fff;
border: 1px solid #e0e0e0;
border-radius: 8px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
display: none;
font-size: 13px;
color: #333;
}
#keyword-block-panel .kb-title {
display: block;
margin-bottom: 8px;
font-weight: 600;
}
#keyword-block-panel .kb-count {
display: block;
margin: -4px 0 8px;
font-size: 12px;
color: #999;
}
#keyword-input {
box-sizing: border-box;
width: 100%;
height: 100px;
padding: 6px 8px;
font-size: 13px;
border: 1px solid #ddd;
border-radius: 6px;
resize: vertical;
outline: none;
}
#keyword-input:focus {
border-color: #aaa;
}
#keyword-block-panel .kb-footer {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 10px;
}
#keyword-clear {
padding: 6px 16px;
font-size: 13px;
color: #666;
background: #f0f0f0;
border: 1px solid #ddd;
border-radius: 6px;
cursor: pointer;
transition: background 0.15s ease;
}
#keyword-clear:hover {
background: #e6e6e6;
}
#keyword-save {
padding: 6px 16px;
font-size: 13px;
color: #fff;
background: #007bff;
border: none;
border-radius: 6px;
cursor: pointer;
transition: background 0.15s ease;
}
#keyword-save:hover {
background: #0069d9;
}

/* ---- 深色主题适配(检测到深色背景时由 JS 加 .nsk-dark) ---- */
#keyword-block-btn.nsk-dark {
color: #ddd;
background: #2c2c2c;
border-color: #4a4a4a;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
}
#keyword-block-btn.nsk-dark:hover {
background: #383838;
}
#keyword-block-btn.nsk-dark:active {
background: #444;
}
#keyword-block-panel.nsk-dark {
background: #1f1f1f;
border-color: #3a3a3a;
color: #ddd;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5);
}
#keyword-block-panel.nsk-dark .kb-count {
color: #888;
}
#keyword-block-panel.nsk-dark #keyword-input {
background: #2a2a2a;
border-color: #4a4a4a;
color: #eee;
}
#keyword-block-panel.nsk-dark #keyword-input:focus {
border-color: #666;
}
#keyword-block-panel.nsk-dark #keyword-clear {
color: #ccc;
background: #2c2c2c;
border-color: #4a4a4a;
}
#keyword-block-panel.nsk-dark #keyword-clear:hover {
background: #383838;
}

/* ---- 手机窄屏:面板占满宽度便于操作 ---- */
@media (max-width: 768px) {
#keyword-block-panel {
left: 16px;
right: 16px;
min-width: 0;
max-height: 70vh;
overflow-y: auto;
}
}
`;
document.head.appendChild(style);

/* ---------------- 关键词存取 + 内存缓存 ---------------- */

function getKeywords() {
const stored = localStorage.getItem(STORAGE_KEY);
return stored ? JSON.parse(stored) : [];
}

function saveKeywords(keywords) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(keywords));
refreshKeywordCache();
}

// ✅ 关键词缓存在内存,避免每条帖子都 localStorage + JSON.parse;统一小写、去空
let keywordCache = [];
function refreshKeywordCache() {
keywordCache = getKeywords().map(k => k.toLowerCase().trim()).filter(Boolean);
}
refreshKeywordCache();

/* ---------------- 帖子处理 ---------------- */

function processPost(post) {
// 没有关键词:保证不残留屏蔽状态,且不做多余查询
if (keywordCache.length === 0) {
if (post.classList.contains(BLOCK_CLASS)) post.classList.remove(BLOCK_CLASS);
return;
}
const titleEl = post.querySelector('.post-title');
if (!titleEl) return;

// ✅ textContent 不触发重排(innerText 会强制 reflow)
const title = titleEl.textContent.toLowerCase();
const matched = keywordCache.some(k => title.includes(k));

post.classList.toggle(BLOCK_CLASS, matched);
}

function processAll() {
document.querySelectorAll('.post-list-item').forEach(processPost);
}

/* ---------------- 观察新插入的帖子,插入即处理 ---------------- */

function observePosts() {
const observer = new MutationObserver(mutations => {
// 无关键词时直接跳过,观察器几乎零开销
if (keywordCache.length === 0) return;

for (const m of mutations) {
for (const node of m.addedNodes) {
if (!(node instanceof HTMLElement)) continue;

if (node.matches('.post-list-item')) {
processPost(node);
} else {
const posts = node.querySelectorAll('.post-list-item');
if (posts.length) posts.forEach(processPost);
}
}
}
});
observer.observe(document.body, { childList: true, subtree: true });
}

/* ---------------- 按钮对齐导航栏 ---------------- */

function findNavBar() {
const candidates = document.querySelectorAll('header, nav, [class*="nav"], [class*="header"]');
for (const el of candidates) {
const r = el.getBoundingClientRect();
if (r.top <= 5 && r.height >= 30 && r.height <= 100 && r.width > window.innerWidth * 0.6) {
return el;
}
}
const input = document.querySelector('input');
let el = input;
while (el && el !== document.body) {
const r = el.getBoundingClientRect();
if (r.top <= 5 && r.height >= 30 && r.height <= 100 && r.width > window.innerWidth * 0.6) {
return el;
}
el = el.parentElement;
}
return null;
}

// 检测页面是否为深色主题(按 body 背景亮度判断)
function isDarkTheme() {
const bg = getComputedStyle(document.body).backgroundColor;
const m = bg.match(/\d+/g);
if (!m) return false;
const [r, g, b] = m.map(Number);
const luminance = 0.299 * r + 0.587 * g + 0.114 * b;
return luminance < 128;
}

// 最近公共祖先工具(v4.6 验证可用)
function getAncestors(node) {
const arr = [];
for (let el = node; el; el = el.parentElement) arr.push(el);
return arr;
}
function lca2(a, b) {
const setA = new Set(getAncestors(a));
for (let el = b; el; el = el.parentElement) if (setA.has(el)) return el;
return null;
}
function directChild(parent, node) {
let el = node;
while (el && el.parentElement !== parent) el = el.parentElement;
return el;
}

// 用渲染坐标取顶栏右侧的一组图标,按从左到右排序返回(手机端用)
function findHeaderIcons() {
const icons = [...document.querySelectorAll('svg')].filter(svg => {
const r = svg.getBoundingClientRect();
return r.width > 0 && r.height > 0 &&
r.top >= 0 && r.top < 70 &&
r.left > window.innerWidth * 0.5;
});
if (icons.length < 2) return null;
icons.sort((a, b) => a.getBoundingClientRect().left - b.getBoundingClientRect().left);
return icons;
}

// 漏斗(过滤)图标,stroke 用 currentColor 以跟随顶栏配色
const FILTER_ICON = '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"></polygon></svg>';

// 用 transform 把按钮中心精确对齐到参考图标的中心(延后测量 + 限幅,避免异常时移出视野)
function alignVertically(btn, refEl) {
if (!refEl) return;
requestAnimationFrame(() => {
btn.style.transform = 'none';
const br = btn.getBoundingClientRect();
const rr = refEl.getBoundingClientRect();
if (!br.height || !rr.height) return;
let dy = (rr.top + rr.height / 2) - (br.top + br.height / 2);
dy = Math.max(-16, Math.min(16, dy));
if (Math.abs(dy) > 0.5) btn.style.transform = `translateY(${dy}px)`;
});
}

function positionButton(btn) {
if (window.innerWidth <= 768) return; // 手机端不走悬浮逻辑
const sw = document.querySelector('.color-theme-switcher');
const ref = (sw && sw.querySelector('svg')) || sw;
if (ref) {
// 按灯泡「图标本身」定位(而非外层 div),才能贴近
const r = ref.getBoundingClientRect();
const btnH = btn.offsetHeight || 28;
btn.style.top = Math.max(0, r.top + r.height / 2 - btnH / 2) + 'px';
btn.style.right = (window.innerWidth - r.left - 4) + 'px'; // 紧贴灯泡左侧
btn.style.left = 'auto';
alignVertically(btn, ref); // 垂直对齐灯泡图标中心
} else {
// 找不到灯泡:退化为对齐顶栏
const nav = findNavBar();
if (nav) {
const btnH = btn.offsetHeight || 32;
const r = nav.getBoundingClientRect();
btn.style.top = Math.max(0, r.top + (r.height - btnH) / 2) + 'px';
}
}
}

/* ---------------- UI ---------------- */

function setupUI() {
if (document.getElementById('keyword-block-btn')) return;

const dark = isDarkTheme();

const btn = document.createElement('button');
btn.id = 'keyword-block-btn';
btn.title = '关键词屏蔽';

// 手机端把按钮嵌入顶栏铃铛左边;电脑端用悬浮文字按钮
const isMobile = window.innerWidth <= 768;
let inserted = false;

const applyIcon = (refEl, cell) => {
btn.classList.add('nsk-inline');
btn.innerHTML = FILTER_ICON;
// 尺寸对齐锚点图标
const size = Math.round(refEl.getBoundingClientRect().width) || 22;
const ourSvg = btn.querySelector('svg');
ourSvg.setAttribute('width', size);
ourSvg.setAttribute('height', size);
// 内边距对齐
if (cell && cell !== refEl) {
btn.style.padding = getComputedStyle(cell).padding;
}
};

if (isMobile) {
// 手机端:锚定最左的铃铛(沿用已验证可用的逻辑),插到它左边
const icons = findHeaderIcons();
if (icons) {
const anchorSvg = icons[0];
const bar = icons.reduce((acc, n) => acc ? lca2(acc, n) : n, null);
const anchorCell = bar && directChild(bar, anchorSvg);
if (bar && anchorCell) {
applyIcon(anchorSvg, anchorCell);
bar.insertBefore(btn, anchorCell);
alignVertically(btn, anchorSvg); // 垂直对齐铃铛
inserted = true;
}
}
}

if (!inserted) {
// 电脑端(及手机端兜底):悬浮漏斗图标,固定在灯泡左侧、跟随黑夜模式
btn.classList.add('nsk-icon');
if (dark) btn.classList.add('nsk-icon-dark');
btn.innerHTML = FILTER_ICON;

// 尺寸 + 颜色对齐灯泡图标
const sw = document.querySelector('.color-theme-switcher');
const refSvg = sw && sw.querySelector('svg');
if (refSvg) {
const size = Math.round(refSvg.getBoundingClientRect().width) || 18;
const ourSvg = btn.querySelector('svg');
ourSvg.setAttribute('width', size);
ourSvg.setAttribute('height', size);
}
// 颜色直接取原生图标的计算颜色(深色模式下自动够白,和齿轮/灯泡同色)
const nativeColor = refSvg ? getComputedStyle(refSvg).color
: (sw ? getComputedStyle(sw).color : '');
if (nativeColor) btn.style.color = nativeColor;

document.body.appendChild(btn);
positionButton(btn);
window.addEventListener('resize', () => positionButton(btn));
}

const panel = document.createElement('div');
panel.id = 'keyword-block-panel';
if (dark) panel.classList.add('nsk-dark');
panel.innerHTML = `
<span class="kb-title">屏蔽关键词(每行一个)</span>
<span class="kb-count" id="kb-count"></span>
<textarea id="keyword-input" placeholder="例如:广告&#10;测评&#10;白嫖"></textarea>
<div class="kb-footer">
<button id="keyword-clear">清除</button>
<button id="keyword-save">保存</button>
</div>
`;
document.body.appendChild(panel);

const input = panel.querySelector('#keyword-input');
const countEl = panel.querySelector('#kb-count');

function doSave() {
const keywords = input.value.split('\n').map(k => k.trim()).filter(Boolean);
saveKeywords(keywords);
processAll();
panel.style.display = 'none';
}

function doClear() {
input.value = '';
saveKeywords([]); // 清空已保存的关键词
processAll(); // 重新处理:所有帖子恢复显示
countEl.textContent = '';
input.focus(); // 面板保持打开,便于重新输入
}

btn.addEventListener('click', () => {
const show = panel.style.display === 'none' || !panel.style.display;
if (show) {
input.value = getKeywords().join('\n');
const blocked = document.querySelectorAll('.post-list-item.' + BLOCK_CLASS).length;
countEl.textContent = blocked ? `本页已屏蔽 ${blocked} 条` : '';
const r = btn.getBoundingClientRect();
panel.style.top = (r.bottom + 8) + 'px';
}
panel.style.display = show ? 'block' : 'none';
});

panel.querySelector('#keyword-save').addEventListener('click', doSave);
panel.querySelector('#keyword-clear').addEventListener('click', doClear);

// 点击面板和按钮以外区域时自动收起
document.addEventListener('click', (e) => {
if (panel.style.display === 'block' &&
!panel.contains(e.target) &&
!btn.contains(e.target)) {
panel.style.display = 'none';
}
});
}

/* ---------------- 启动 ---------------- */

// body 一就绪就启动观察器:帖子插入的瞬间即处理,命中帖在浏览器绘制前就被隐藏,最大限度减少闪现
(function startWhenBodyReady() {
if (!document.body) {
requestAnimationFrame(startWhenBodyReady);
return;
}
observePosts(); // 之后插入的帖子即时处理
processAll(); // 处理此刻已存在的帖子

// 按钮 UI 依赖页面结构,等首条帖子出现再装
const ui = setInterval(() => {
if (document.querySelector('.post-list-item')) {
clearInterval(ui);
processAll();
setupUI();
}
}, 100);
})();
})();
最新回复 (6)
  • BiggerIan 06-18 01:24
    1

    技术贴送鸡腿 + 点赞 + 收藏,万一以后用得到呢 ^-^ ^-^ ^-^

  • 快乐的出帆 06-18 01:38
    2

    佬,建议直接做成谷歌浏览器插件,猴脚本我估计很多人不知道怎么用 ^-^

  • Maose 06-18 02:11
    3

    @快乐的出帆 #2

    都来这个论坛了,不至于用不来吧 ^-^

  • 快乐的出帆 06-18 02:12
    4

    @Maose #3 小白多着呢

  • Wdysxy1234-我 06-18 06:55
    5

    @guyuege #0 感谢分享

  • LogicNova 06-18 07:32
    6

    感谢分享,先收了

* 帖子来源NodeSeek
返回