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

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

目前為 2025-09-23 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 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 */