哔哩哔哩-Bilibili-B站搜索结果过滤(兼容Bilibili旧播放页)

根据输入实时隐藏包含指定关键词的网页元素,支持动态内容更新

// ==UserScript==
// @name         哔哩哔哩-Bilibili-B站搜索结果过滤(兼容Bilibili旧播放页)
// @version      0.1
// @description  根据输入实时隐藏包含指定关键词的网页元素,支持动态内容更新
// @author       rteta-gpt4o
// @match        https://search.bilibili.com/*
// @license MIT
// @namespace https://greasyfork.org/users/1217761
// ==/UserScript==

(function() {
    'use strict';

    // 创建悬浮输入框
    var inputBox = document.createElement('textarea');
    inputBox.style.position = 'fixed';
    inputBox.style.left = '10px';
    inputBox.style.bottom = '10px';
    inputBox.style.width = '180px';
    inputBox.style.height = '70px';
    inputBox.style.zIndex = '9999';
    inputBox.style.border = '1px solid #ccc';
    inputBox.style.padding = '10px';
    inputBox.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.2)';
    inputBox.placeholder = '输入要隐藏的关键词,用英文逗号分隔';
    document.body.appendChild(inputBox);

    // 定义一个变量保存当前的关键词
    let keywords = [];

    // 过滤函数,用于隐藏或显示li和.video-list下的div元素
    function filterListItems() {
        // 处理 ul > li 的情况
        var ulElements = document.querySelectorAll('ul');
        ulElements.forEach(function(ul) {
            var liElements = ul.querySelectorAll('li');
            liElements.forEach(function(li) {
                var liText = li.textContent.trim();
                // 如果li包含任何关键词则隐藏,否则显示
                if (keywords.length > 0 && keywords.some(function(keyword) {
                    return liText.includes(keyword);
                })) {
                    li.style.display = 'none';
                } else {
                    li.style.display = '';  // 恢复显示
                }
            });
        });

        // 处理 .video-list > div 的情况
        var videoListDivs = document.querySelectorAll('.video-list > div');
        videoListDivs.forEach(function(div) {
            var divText = div.textContent.trim();
            // 如果div包含任何关键词则隐藏,否则显示
            if (keywords.length > 0 && keywords.some(function(keyword) {
                return divText.includes(keyword);
            })) {
                div.style.display = 'none';
            } else {
                div.style.display = '';  // 恢复显示
            }
        });
    }

    // 实时监听输入框内容变化
    inputBox.addEventListener('input', function() {
        var inputValue = inputBox.value.trim();
        keywords = inputValue ? inputValue.split(',').map(function(keyword) {
            return keyword.trim();
        }) : [];

        filterListItems();
    });

    // 观察页面中ul、li以及.video-list div元素的变化
    var observer = new MutationObserver(function(mutations) {
        // 当检测到 DOM 变化时,重新执行过滤操作
        mutations.forEach(function(mutation) {
            if (mutation.addedNodes.length || mutation.removedNodes.length) {
                filterListItems();
            }
        });
    });

    // 开始观察整个文档,监听子元素的变化
    observer.observe(document.body, {
        childList: true,  // 监听直接子元素的变化
        subtree: true,    // 监听所有后代元素的变化
    });

})();