Bilibili 自动开启字幕 (支持模糊匹配)

辣鸡 B 站到 2025 年还不支持自动开启字幕

当前为 2025-09-23 提交的版本,查看 最新版本

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。

您需要先安装用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         Bilibili 自动开启字幕 (支持模糊匹配)
// @namespace    http://tampermonkey.net/
// @description  辣鸡 B 站到 2025 年还不支持自动开启字幕
// @version      1.2
// @author       Yuna
// @match        *://www.bilibili.com/video/*
// @grant        GM_registerMenuCommand
// @run-at       document-end
// @license      MIT
// ==/UserScript==

'use strict';

function enableSubtitle ()
{
    /* 排序越是靠前的字幕优先级越高 */
    const priorityList = [
        { name: "英语", selector: ".bpx-player-ctrl-subtitle-language-item[data-lan *= 'en-']" },
        { name: "AI英语", selector: ".bpx-player-ctrl-subtitle-language-item[data-lan *= 'ai-en']" },
        { name: "中文字幕", selector: ".bpx-player-ctrl-subtitle-language-item[data-lan *= 'h-']" },
        { name: "AI中文字幕", selector: ".bpx-player-ctrl-subtitle-language-item[data-lan *= 'ai-zh']" }
    ];

    for ( const item of priorityList )
    {
        const language = document.querySelector( item.selector );
        
        // 检测是否存在该语言,如果存在且未被选中,则点击,并返回
        if ( language && !language.className.includes( "bpx-state-active" ) )
        {
            language.querySelector( ".bpx-player-ctrl-subtitle-language-item-text" )
                    .click();
            console.info( `已开启${ item.name }字幕` );
            notification( `已开启${ item.name }字幕` );
            return;
        }
    }

    console.info( "未找到可用的字幕" );
    notification( "未找到可用的字幕" );
    setTimeout( enableSubtitle, 2000 );
}

/**
 * 显示通知, Hook 到 Bilibili 字幕设置页面
 * @param message str   希望显示的消息
 * @param timeoutOfMS int   通知显示的时长, 单位为毫秒
 */
function notification ( message, timeoutOfMS = 3000 )
{
    const notificationBox = document.querySelector( ".bpx-player-toast-auto" );

    const notificationItem = document.createElement( "div" );
    notificationItem.innerHTML = `
            <div class = "bpx-player-toast-row bpx-player-toast-unfold">
        <div class = "bpx-player-toast-item"><span class = "bpx-player-toast-text">${ message }</span>
        </div>
    </div>
    `;

    notificationBox.appendChild( notificationItem );

    setTimeout( () => notificationItem.remove(), timeoutOfMS );
}

notification( "正在尝试自动开启字幕" );
setInterval( enableSubtitle, 2000 );    /* 实在是不知道怎么在播放器加载后就自动开启字幕,所以暂时用这个,每 2 秒尝试一次,如果有更好的方法,欢迎提 issue */