BROWSER BOOKMARKLET · V2.2
B站本地视频播放
在 Bilibili 普通视频网页中播放本地视频,保留原生播放器功能及原视频弹幕。无需安装扩展。
01 / 添加到浏览器书签
- 打开浏览器的书签栏 / 收藏夹栏。Windows 通常按 Ctrl + Shift + B,Mac Safari 可从“显示”菜单开启个人收藏栏。
- 将下方蓝色链接拖到书签栏(不是点击链接)。
B站本地视频播放 V2.2
加入书签栏后即可运行。
拖拽不可用?手动添加书签
新建任意书签,设置名字并编辑其网址 / 地址,将下面的全部内容粘贴后并保存。不要粘贴到浏览器地址栏。
02 / 在 B 站使用
- 打开一个 B 站普通视频页面,等待原播放器加载完成。
- 点击书签栏里的“B站本地视频播放”。
- 在页面右上角点击“选择本地视频”,选取电脑中的视频文件,工具先检测视频能否解码,成功后接管原播放器(部分浏览器可能需要手动点击播放)。
- 再次点击书签,选择“更换本地视频”,无需刷新即可换文件;检测失败保留当前视频。刷新页面恢复原 B 站视频。
兼容性与隐私
适用于支持 JavaScript 书签的浏览器,仅支持普通 B 站视频页,推荐 MP4(H.264 + AAC)。检测、接管和加载各有 15 秒超时;预检测不保证所有音轨和后续帧均可解码。初次接管失败可能需要刷新;更换本地视频失败时尝试恢复上一个文件。
V2.2:尝试关闭自动连播,监控视频源与 BV、分 P、CID 变化。允许手动换集恢复到原视频,发现切换时退出本地模式并清理资源,且将恢复连播设置,部分异常退出可能无法恢复需刷新网页。新版已在 Chromium 模拟播放器中测试,跨浏览器兼容性待验证。
本工具没有上传文件、远程代码加载或统计功能。但它在 B 站网页的Scope中运行,网站脚本理论上存在访问载入的视频资源的可能性,因此请勿选择敏感或私密视频。
查看完整脚本源代码
(() => {
// Bili Local Video v2.2. No external dependencies.
const w = window, d = document, key = '__biliLocalVideoV22';
const sid = 'bili-local-video-style', pid = 'bili-local-bookmarklet-panel';
if (!['www.bilibili.com', 'bilibili.com'].includes(location.hostname) || !location.pathname.startsWith('/video/')) {
alert('请先打开B站普通视频页。'); return;
}
if (w[key]) { w[key].open(); return; }
if (d.getElementById(sid) || d.getElementById(pid) || w.__biliLocalVideoV21) {
alert('旧版仍在运行,请刷新。'); return;
}
const p = w.player;
let c, e, v;
try {
c = p.__core(); e = c.getCorePlayer(); v = p.mediaElement();
if (!(v instanceof HTMLVideoElement) || !v.isConnected ||
![e.attachSource, e.setScheduleWhilePaused, e.seek, c.seek, p.seek,
p.setSegmented, p.addViewPoints, p.setAIPoints].every(f => typeof f === 'function')) throw 0;
} catch (_) { alert('播放器未就绪或不兼容。'); return; }
// Compare video identity, not unrelated URL query parameters (e.g. t, spm_id_from).
const route = () => {
const path = location.pathname;
const part = new URLSearchParams(location.search).get('p');
return (path.endsWith('/') ? path.slice(0, -1) : path) + ':' + (Number(part) || 1);
};
const fields = ['aid', 'bvid', 'cid', 'p'];
const manifest = () => {
try { const m = p.getManifest?.(); return fields.map(k => m?.[k] == null ? null : String(m[k])); }
catch (_) { return []; }
};
const initial = route(), ids = manifest();
const samePlayer = () => {
try { return w.player === p && p.__core() === c && c.getCorePlayer() === e && p.mediaElement() === v && v.isConnected; }
catch (_) { return false; }
};
const samePart = () => {
if (route() !== initial || !samePlayer()) return false;
const now = manifest();
return !ids.some((x, i) => x != null && now[i] != null && x !== now[i]);
};
const make = tag => d.createElement(tag);
const urls = new Set(), abort = new AbortController();
let box, busy = false, closed = false, detached = false, switching = false;
let active, expected, style, timer, seek, originals, beforeHandoff, changedHandoff = false, scheduleBefore;
const session = { open };
w[key] = session;
const release = url => { if (urls.delete(url)) URL.revokeObjectURL(url); };
const hide = () => { box?.remove(); box = null; busy = false; };
const owns = () => !!expected && v.src === expected && !v.srcObject;
// Use the player's documented-by-community handoff enum, never guess its numeric value.
// Only change a setting we can read back and restore. End-event capture is the fallback.
const handoff = () => {
try {
const off = w.nano?.HandoffKind?.Abort;
const old = p.getHandoff?.();
if (off == null || !['number', 'string', 'boolean'].includes(typeof old) || typeof p.setHandoff !== 'function') return false;
if (old === off) return true;
beforeHandoff = old; changedHandoff = true;
p.setHandoff(off);
return p.getHandoff() === off;
} catch (_) { return false; }
};
const restoreHandoff = () => {
try {
if (changedHandoff && w.player === p && p.getHandoff() === w.nano?.HandoffKind?.Abort) p.setHandoff(beforeHandoff);
} catch (_) {}
changedHandoff = false;
};
const onEnded = event => {
if (event.target !== v || closed || !owns() || !samePart()) return;
if (!handoff()) { event.stopImmediatePropagation(); v.pause(); }
};
// Dispose just our modifications. Never pause/overwrite a new remote source.
function exit(reason, lock = false, silent = false) {
if (closed) return;
closed = true;
abort.abort(); clearInterval(timer);
for (const name of ['loadstart', 'emptied', 'loadedmetadata', 'playing']) v.removeEventListener(name, check);
v.removeEventListener('error', mediaError);
d.removeEventListener('ended', onEnded, true);
w.removeEventListener('popstate', check);
w.removeEventListener('pagehide', onHide);
w.removeEventListener('pageshow', onShow);
restoreHandoff();
try { if (typeof scheduleBefore === 'boolean' && e.getScheduleWhilePaused?.() === false) e.setScheduleWhilePaused(scheduleBefore); } catch (_) {}
if (originals) [e, c, p].forEach((o, i) => { if (o.seek === seek) o.seek = originals[i]; });
style?.remove(); hide();
if (owns()) {
v.pause(); v.removeAttribute('src'); v.load();
}
for (const url of urls) release(url);
if (w[key] === session) {
if (lock) w[key] = { open: () => alert('请刷新后重试。') };
else delete w[key];
}
if (reason && !silent) alert(reason);
}
function check() {
if (closed) return false;
if (!samePart()) {
exit('已换集或切换视频,退出本地模式。若原视频未恢复,请刷新。', detached && !originals); return false;
}
if (expected && (!owns() || (!switching && v.currentSrc && v.currentSrc !== expected))) {
exit('检测到视频源变更,已退出本地模式。若播放异常,请刷新。'); return false;
}
return true;
}
function mediaError() {
if (!switching && check() && owns()) exit('视频解码失败,请刷新。', true);
}
function onHide(event) {
if (event.persisted) { restoreHandoff(); return; }
exit('', false, true);
}
function onShow() { if (check() && detached) handoff(); }
const monitor = () => {
for (const name of ['loadstart', 'emptied', 'loadedmetadata', 'playing']) v.addEventListener(name, check);
v.addEventListener('error', mediaError);
d.addEventListener('ended', onEnded, true);
w.addEventListener('popstate', check);
w.addEventListener('pagehide', onHide);
w.addEventListener('pageshow', onShow);
// Also detects SPA pushState and internal player changes while paused.
timer = setInterval(check, 1000);
};
// All media waits are bounded and abortable; listeners are removed on any exit.
const wait = (m, url, start) => new Promise((resolve, reject) => {
let t;
const finish = error => {
clearTimeout(t); m.removeEventListener('loadeddata', ready);
m.removeEventListener('error', fail); abort.signal.removeEventListener('abort', stop);
error ? reject(error) : resolve();
};
const ready = () => { if (m.src === url && m.readyState >= 2) finish(); };
const fail = () => finish(new Error('无法解码,建议MP4'));
const stop = () => finish(new Error('操作已取消'));
if (abort.signal.aborted) { stop(); return; }
t = setTimeout(() => finish(new Error('加载超时')), 15000);
m.addEventListener('loadeddata', ready); m.addEventListener('error', fail);
abort.signal.addEventListener('abort', stop, { once: true });
try { start(); } catch (err) { finish(err); }
});
const bounded = fn => new Promise((resolve, reject) => {
let t;
const finish = (f, x) => { clearTimeout(t); abort.signal.removeEventListener('abort', stop); f(x); };
const stop = () => finish(reject, new Error('操作已取消'));
if (abort.signal.aborted) { stop(); return; }
t = setTimeout(() => finish(reject, new Error('接管超时')), 15000);
abort.signal.addEventListener('abort', stop, { once: true });
Promise.resolve().then(fn).then(x => finish(resolve, x), x => finish(reject, x));
});
const probeFile = async url => {
const probe = make('video'); probe.preload = 'auto'; probe.muted = probe.playsInline = true;
try {
await wait(probe, url, () => { probe.src = url; probe.load(); });
if (!probe.videoWidth || !Number.isFinite(probe.duration) || probe.duration <= 0) throw new Error('无有效视频画面');
} finally { probe.removeAttribute('src'); probe.load(); }
};
const load = async url => {
switching = true; expected = url;
await wait(v, url, () => { v.pause(); v.srcObject = null; v.preload = 'auto'; v.src = url; v.load(); });
if (!check()) throw new Error('播放器已变更');
if (!v.videoWidth || !Number.isFinite(v.duration) || v.duration <= 0) throw new Error('无有效视频画面');
switching = false;
};
const cleanUI = () => {
if (!style) {
style = make('style'); style.id = sid;
style.textContent = '.bpx-player-ctrl-quality,.bpx-player-ctrl-quality-menu-wrap,.bpx-player-progress-preview-image,.bpx-player-pbp{display:none!important}';
d.head.appendChild(style);
}
try { p.setSegmented('[]'); p.addViewPoints('[]'); p.setAIPoints([]); }
catch (_) { console.warn('[Local Video] UI cleanup incomplete'); }
};
const play = async url => {
try { await v.play(); }
catch (err) {
if (closed || expected !== url || !owns()) return;
if (err.name === 'NotAllowedError') alert('请手动点击播放。');
else if (err.name !== 'AbortError') exit('播放失败,请刷新。', true);
}
};
async function select(file, hint) {
const old = active;
let url, snapshot, attempted = false;
try {
if (!check()) return;
url = URL.createObjectURL(file); urls.add(url);
hint.textContent = '正在检测视频…';
await probeFile(url);
if (!check()) return;
hint.textContent = '正在加载…';
if (!detached) {
detached = true;
v.pause();
try { scheduleBefore = e.getScheduleWhilePaused?.(); } catch (_) {}
e.setScheduleWhilePaused(false);
monitor();
await bounded(() => e.attachSource(null));
if (!check()) return;
originals = [e.seek, c.seek, p.seek];
seek = time => {
time = Number(time);
if (owns() && Number.isFinite(time) && Number.isFinite(v.duration)) v.currentTime = Math.max(0, Math.min(time, v.duration));
};
e.seek = c.seek = p.seek = seek;
handoff();
} else {
snapshot = { time: v.currentTime, paused: v.paused, rate: v.playbackRate };
}
attempted = true;
await load(url);
if (!check()) return;
if (snapshot) v.playbackRate = snapshot.rate;
cleanUI(); handoff();
active = url;
if (old) release(old);
hide();
console.log('[Local Video] OK');
await play(url);
} catch (err) {
if (closed || !check()) return;
const msg = err?.message || '无法播放';
if (old && attempted && snapshot) {
// The old URL remains valid until the replacement is committed.
try {
await load(old);
if (!check()) return;
active = old; release(url);
v.currentTime = Math.min(snapshot.time, v.duration); v.playbackRate = snapshot.rate;
cleanUI(); handoff(); hide();
if (!snapshot.paused) await play(old);
if (!closed) alert(msg + ',已恢复上一个本地视频。');
} catch (_) { if (!closed) exit('恢复失败,请刷新。', true); }
} else if (!attempted && (old || !detached)) {
release(url); hide();
if (!old) exit('', false, true);
alert(msg + (old ? ',仍保留上一个本地视频。' : ',未替换原视频。'));
} else { exit(msg + ',请刷新。', true); }
}
}
function open() {
if (closed || !check() || busy || box) return;
const hint = make('div'), input = make('input'), choose = make('button'), close = make('button');
box = make('div'); box.id = pid;
box.style.cssText = 'position:fixed;top:16px;right:16px;z-index:2147483647;background:#fff;color:#222;padding:16px;border-radius:10px;box-shadow:0 6px 28px #0005;font:14px system-ui,sans-serif;max-width:min(340px,85vw);text-align:left';
hint.textContent = '网页脚本可能读取文件,请勿选择私密视频。'; hint.style.marginBottom = '12px';
input.type = 'file'; input.accept = 'video/*,.mp4,.webm,.mov,.m4v,.mkv'; input.hidden = true;
choose.type = close.type = 'button'; choose.textContent = active ? '更换本地视频' : '选择本地视频'; close.textContent = '取消';
choose.style.cssText = close.style.cssText = 'border:0;border-radius:6px;padding:9px 14px;cursor:pointer';
choose.style.background = '#007aa5'; choose.style.color = '#fff'; close.style.marginLeft = '8px'; close.style.background = '#eee'; close.style.color = '#222';
close.onclick = () => { hide(); if (!detached) exit('', false, true); };
choose.onclick = () => input.click();
input.onchange = () => {
const file = input.files[0]; if (!file || busy || closed) return;
input.value = ''; busy = choose.disabled = close.disabled = true;
select(file, hint);
};
box.append(hint, choose, close, input); (d.fullscreenElement || d.body).appendChild(box);
}
open();
})();