懒人福音 省去复制粘贴 B 站链接转换脚本

11 天前
 icelei

起因

在浏览帖子时经常遇到某站的视频 id ,想进一步看是什么视频的时候都要通过 复制→进入视频网站→粘贴并回车 这样一个过程才能完成。作为一个懒人,想直接可以点击访问,于是有了这个脚本。

主要功能

将页面中的某站视频 ID ( BV 号或 av 号)转换为可点击链接

代码如下

// ==UserScript==
// @name         B 站链接转换器
// @namespace    icelo0@126.com
// @version      0.1
// @description  将页面中的 B 站视频 ID ( BV 号或 av 号)转换为可点击链接
// @author       iceLei
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    function replaceIdsWithLinks() {
        const pattern = /(?:BV[0-9A-Za-z]{10,}|av\d+)/g;
        
        // 递归处理文本节点
        function walk(node) {
            if (node.nodeType === 3) { // 文本节点
                const text = node.nodeValue;
                const matches = text.match(pattern);
                if (matches) {
                    const fragment = document.createDocumentFragment();
                    let lastIndex = 0;
                    
                    text.replace(pattern, (match, index) => {
                        // 添加匹配前的文本
                        fragment.appendChild(document.createTextNode(text.slice(lastIndex, index)));
                        
                        // 创建链接元素
                        const link = document.createElement('a');
                        link.href = `https://www.bilibili.com/video/${match}`;
                        link.textContent = match;
                        link.target = '_blank';
                        link.style.color = '#FB7299'; // B 站粉色
                        link.style.textDecoration = 'underline';
                        
                        fragment.appendChild(link);
                        lastIndex = index + match.length;
                    });
                    
                    // 添加剩余文本
                    fragment.appendChild(document.createTextNode(text.slice(lastIndex)));
                    
                    // 替换原节点
                    node.parentNode.replaceChild(fragment, node);
                }
            } else if (node.nodeType === 1 && node.tagName !== 'A') { // 元素节点且不是链接
                // 递归处理子节点
                Array.from(node.childNodes).forEach(walk);
            }
        }
        
        walk(document.body);
    }

    // 执行替换
    replaceIdsWithLinks();
})();
1133 次点击
所在节点    分享创造
1 条回复
chendaye
11 天前
没处理未来元素吗?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://ex.noerr.eu.org/t/1162653

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX