// ==UserScript== // @name bilibili 视频弹幕统计|下载|查询发送者 // @namespace https://github.com/ZBpine/bili-danmaku-statistic // @version 1.5.3 // @description 获取B站视频页弹幕数据,并生成统计页面 // @author ZBpine // @icon https://i0.hdslb.com/bfs/static/jinkela/long/images/favicon.ico // @match https://www.bilibili.com/video/* // @match https://www.bilibili.com/list/watchlater* // @match https://space.bilibili.com/* // @grant none // @license MIT // @run-at document-end // @downloadURL none // ==/UserScript== (function () { 'use strict'; // iframe里初始化Vue应用 async function initIframeApp(iframe, dataParam, panelInfoParam) { const doc = iframe.contentDocument; const win = iframe.contentWindow; // 引入外部库 const addScript = (src) => new Promise(resolve => { const script = doc.createElement('script'); script.src = src; script.onload = resolve; doc.head.appendChild(script); }); const addCss = (href) => { const link = doc.createElement('link'); link.rel = 'stylesheet'; link.href = href; doc.head.appendChild(link); }; addCss('https://cdn.jsdelivr.net/npm/element-plus/dist/index.css'); await addScript('https://cdn.jsdelivr.net/npm/vue@3.3.4/dist/vue.global.prod.js'); await addScript('https://cdn.jsdelivr.net/npm/element-plus/dist/index.full.min.js'); await addScript('https://cdn.jsdelivr.net/npm/echarts@5'); await addScript('https://cdn.jsdelivr.net/npm/echarts-wordcloud@2/dist/echarts-wordcloud.min.js'); await addScript('https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js'); await addScript('https://cdn.jsdelivr.net/npm/dom-to-image-more@3.5.0/dist/dom-to-image-more.min.js'); // 创建挂载点 const appRoot = doc.createElement('div'); appRoot.id = 'danmaku-app'; doc.body.style.margin = '0'; doc.body.appendChild(appRoot); // 挂载Vue const { createApp, ref, onMounted, nextTick } = win.Vue; const ELEMENT_PLUS = win.ElementPlus; const ECHARTS = win.echarts; const app = createApp({ setup() { const displayedDanmakus = ref([]); const filterText = ref('^(哈|呵|h|ha|HA|H+|233+)+$'); const originDanmakuCount = ref(0); const currentFilt = ref(''); const currentSubFilt = ref({}); const danmakuCount = ref({ user: 0, dm: 0 }); const videoData = ref(dataParam.videoData); const isTableVisible = ref(true); const isTableAutoH = ref(false); const loading = ref(true); const isExpandedUserChart = ref(false); const panelInfo = ref(panelInfoParam); const visibleCharts = ref(['user', 'wordcloud', 'density', 'date', 'hour']); const chartHover = ref(null); const charts = { user: null, wordcloud: null, density: null, date: null, hour: null }; let manager = null; class DanmakuManager { constructor(danmakuList) { this.original = [...danmakuList].sort((a, b) => a.progress - b.progress); this.filtered = [...this.original]; // 保持同步顺序 } reset() { this.filtered = [...this.original]; } filter(regex) { this.filtered = this.original.filter(d => regex.test(d.content)); } getStats() { const countMap = {}; for (const d of this.filtered) { countMap[d.midHash] = (countMap[d.midHash] || 0) + 1; } return Object.entries(countMap) .map(([user, count]) => ({ user, count })) .sort((a, b) => b.count - a.count); } } const biliCrc2Mid = function () { /* 函数来源 https://github.com/shafferjohn/bilibili-search/blob/master/crc32.js */ const CRCPOLYNOMIAL = 0xEDB88320; var startTime = new Date().getTime(), crctable = new Array(256), create_table = function () { var crcreg, i, j; for (i = 0; i < 256; ++i) { crcreg = i; for (j = 0; j < 8; ++j) { if ((crcreg & 1) != 0) { crcreg = CRCPOLYNOMIAL ^ (crcreg >>> 1); } else { crcreg >>>= 1; } } crctable[i] = crcreg; } }, crc32 = function (input) { if (typeof (input) != 'string') input = input.toString(); var crcstart = 0xFFFFFFFF, len = input.length, index; for (var i = 0; i < len; ++i) { index = (crcstart ^ input.charCodeAt(i)) & 0xff; crcstart = (crcstart >>> 8) ^ crctable[index]; } return crcstart; }, crc32lastindex = function (input) { if (typeof (input) != 'string') input = input.toString(); var crcstart = 0xFFFFFFFF, len = input.length, index; for (var i = 0; i < len; ++i) { index = (crcstart ^ input.charCodeAt(i)) & 0xff; crcstart = (crcstart >>> 8) ^ crctable[index]; } return index; }, getcrcindex = function (t) { //if(t>0) //t-=256; for (var i = 0; i < 256; i++) { if (crctable[i] >>> 24 == t) return i; } return -1; }, deepCheck = function (i, index) { var tc = 0x00, str = '', hash = crc32(i); tc = hash & 0xff ^ index[2]; if (!(tc <= 57 && tc >= 48)) return [0]; str += tc - 48; hash = crctable[index[2]] ^ (hash >>> 8); tc = hash & 0xff ^ index[1]; if (!(tc <= 57 && tc >= 48)) return [0]; str += tc - 48; hash = crctable[index[1]] ^ (hash >>> 8); tc = hash & 0xff ^ index[0]; if (!(tc <= 57 && tc >= 48)) return [0]; str += tc - 48; hash = crctable[index[0]] ^ (hash >>> 8); return [1, str]; }; create_table(); var index = new Array(4); console.log('初始化耗时:' + (new Date().getTime() - startTime) + 'ms'); return function (input) { var ht = parseInt('0x' + input) ^ 0xffffffff, snum, i, lastindex, deepCheckData; for (i = 3; i >= 0; i--) { index[3 - i] = getcrcindex(ht >>> (i * 8)); snum = crctable[index[3 - i]]; ht ^= snum >>> ((3 - i) * 8); } for (i = 0; i < 100000000; i++) { lastindex = crc32lastindex(i); if (lastindex == index[3]) { deepCheckData = deepCheck(i, index) if (deepCheckData[0]) break; } } if (i == 100000000) return -1; console.log('总耗时:' + (new Date().getTime() - startTime) + 'ms'); return i + '' + deepCheckData[1]; } } function formatProgress(ms) { const s = Math.floor(ms / 1000); const min = String(Math.floor(s / 60)).padStart(2, '0'); const sec = String(s % 60).padStart(2, '0'); return `${min}:${sec}`; } function formatCtime(t) { const d = new Date(t * 1000); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0') + ' ' + String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0'); } function formatTime(ts) { const d = new Date(ts * 1000); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; } async function shareImage() { const html2canvas = win.html2canvas; const domtoimage = win.domtoimage; if (!html2canvas || !domtoimage) { ELEMENT_PLUS.ElMessage.error('截图库加载失败'); return; } const titleWrapper = doc.getElementById('wrapper-title'); const tableWrapper = doc.getElementById('wrapper-table'); const chartWrapper = doc.getElementById('wrapper-chart'); if (!titleWrapper || !tableWrapper || !chartWrapper) { ELEMENT_PLUS.ElMessage.error('找不到截图区域'); return; } loading.value = true; try { titleWrapper.style.paddingBottom = '10px'; //dom-to-image-more会少截 tableWrapper.style.paddingBottom = '40px'; await nextTick(); const loadImage = (blob) => new Promise((resolve) => { const img = new Image(); img.onload = () => resolve(img); img.src = URL.createObjectURL(blob); }); const scale = window.devicePixelRatio; //title使用dom-to-image-more截图,table和chart使用html2canvas截图 const titleBlob = await domtoimage.toBlob(titleWrapper, { style: { transform: `scale(${scale})`, transformOrigin: 'top left' }, width: titleWrapper.offsetWidth * scale, height: titleWrapper.offsetHeight * scale }); const titleImg = await loadImage(titleBlob); //foreignObjectRendering开启则Echart无法显示,关闭则el-tag没有文字。 // const [titleCanvas, tableCanvas, chartCanvas] = await Promise.all([ // html2canvas(titleWrapper, { // useCORS: true, backgroundColor: '#fff', scale: scale, // foreignObjectRendering: true // }), // html2canvas(tableWrapper, { useCORS: true, backgroundColor: '#fff', scale: scale }), // html2canvas(chartWrapper, { useCORS: true, backgroundColor: '#fff', scale: scale }) // ]); let tableCanvas = null; let chartCanvas = null; if (isTableVisible.value) { tableCanvas = await html2canvas(tableWrapper, { useCORS: true, backgroundColor: '#fff', scale }); } else { tableCanvas = document.createElement('canvas'); tableCanvas.width = 0; tableCanvas.height = 0; } chartCanvas = await html2canvas(chartWrapper, { useCORS: true, backgroundColor: '#fff', scale }); // 计算总大小 const totalWidth = Math.max(titleImg.width, tableCanvas.width, chartCanvas.width) * 1.1; const totalHeight = titleImg.height + tableCanvas.height + chartCanvas.height; // 合并成一张新 canvas const finalCanvas = document.createElement('canvas'); finalCanvas.width = totalWidth; finalCanvas.height = totalHeight; const ctx = finalCanvas.getContext('2d'); // 绘制 ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, totalWidth, totalHeight); let y = 0; ctx.drawImage(titleImg, (totalWidth - titleImg.width) / 2, y); y += titleImg.height; if (tableCanvas.height > 0) { ctx.drawImage(tableCanvas, (totalWidth - tableCanvas.width) / 2, y); y += tableCanvas.height; } if (chartCanvas.height > 0) { ctx.drawImage(chartCanvas, (totalWidth - chartCanvas.width) / 2, y); } // 输出图片 finalCanvas.toBlob(blob => { const blobUrl = URL.createObjectURL(blob); ELEMENT_PLUS.ElMessageBox({ title: '截图预览', dangerouslyUseHTMLString: true, message: ` `, showCancelButton: true, confirmButtonText: '保存图片', cancelButtonText: '关闭', }).then(() => { const link = doc.createElement('a'); link.download = `${videoData.value.bvid}_danmaku_statistics.png`; link.href = blobUrl; link.click(); URL.revokeObjectURL(blobUrl); // 可选:释放内存 }).catch(() => { URL.revokeObjectURL(blobUrl); }); }); } catch (err) { console.error(err); ELEMENT_PLUS.ElMessage.error('截图生成失败'); } finally { titleWrapper.style.paddingBottom = ''; tableWrapper.style.paddingBottom = ''; loading.value = false; } } function midHashOnClick() { if (!currentSubFilt.value.user) return; ELEMENT_PLUS.ElMessageBox.confirm( `是否尝试反查用户ID?

可能需要一段时间,且10位数以上ID容易查错

`, '提示', { dangerouslyUseHTMLString: true, confirmButtonText: '是', cancelButtonText: '否', type: 'warning', } ).then(() => { // 开始反查用户ID var midcrc = new biliCrc2Mid(); var result = midcrc(currentSubFilt.value.user); if (result && result !== '-1') { ELEMENT_PLUS.ElMessageBox.alert( `已查到用户ID: 点击访问用户空间

此ID通过弹幕哈希本地计算得出,非官方公开数据,请谨慎使用

`, '查找成功', { dangerouslyUseHTMLString: true, confirmButtonText: '确定', type: 'success', } ); } else { ELEMENT_PLUS.ElMessage.error('未能查到用户ID或用户不存在'); } }).catch(() => { // 用户点击了取消,只复制midHash navigator.clipboard.writeText(currentSubFilt.value.user).then(() => { ELEMENT_PLUS.ElMessage.success('midHash已复制到剪贴板'); }).catch(() => { ELEMENT_PLUS.ElMessage.error('复制失败'); }); }); } function moveChartUp(chart) { const idx = visibleCharts.value.indexOf(chart); if (idx > 0) { visibleCharts.value.splice(idx, 1); visibleCharts.value.splice(idx - 1, 0, chart); } } function moveChartDown(chart) { const idx = visibleCharts.value.indexOf(chart); if (idx < visibleCharts.value.length - 1) { visibleCharts.value.splice(idx, 1); visibleCharts.value.splice(idx + 1, 0, chart); } } function moveChartOut(chart) { const idx = visibleCharts.value.indexOf(chart); if (idx !== -1) { visibleCharts.value.splice(idx, 1); // 销毁 ECharts 实例 const inst = charts[chart]; if (inst && inst.dispose) { inst.dispose(); charts[chart] = null; } } } function renderUserChart(stats) { const el = doc.getElementById('chart-user'); if (!el) return; if (!charts.user) { el.style.height = isExpandedUserChart.value ? '100%' : '50%'; charts.user = ECHARTS.init(el); charts.user.on('click', async (params) => { const selected = params.name; await updateDispDanmakus( manager.filtered.filter(d => d.midHash === selected), { user: selected } ); }); // 点击标题切换展开状态 charts.user.getZr().on('click', function (params) { if (params.offsetY >= 0 && params.offsetY <= 40) { isExpandedUserChart.value = !isExpandedUserChart.value; if (charts.user) { charts.user.dispose(); charts.user = null; } renderUserChart(stats); // 重新绘制 } }); } const userNames = stats.map(item => item.user); const counts = stats.map(item => item.count); const maxCount = Math.max(...counts); const sc = isExpandedUserChart.value ? 20 : 8; charts.user.setOption({ tooltip: {}, title: { text: '用户弹幕统计' }, grid: { left: 100 }, xAxis: { type: 'value', min: 0, max: Math.ceil(maxCount * 1.1), // 横轴最大值略大一点 scale: false }, yAxis: { type: 'category', data: userNames, inverse: true }, dataZoom: [ { type: 'slider', yAxisIndex: 0, startValue: 0, endValue: userNames.length >= sc ? sc - 1 : userNames.length, width: 20 } ], series: [{ type: 'bar', data: counts, label: { show: true, position: 'right', // 在条形右边显示 formatter: '{c}', // 显示数据本身 fontSize: 12 } }] }); } function renderWordCloud(data) { const el = doc.getElementById('chart-wordcloud'); if (!el) return; if (!charts.wordcloud) { charts.wordcloud = ECHARTS.init(el); charts.wordcloud.on('click', async (params) => { const keyword = params.name; const regex = new RegExp(keyword, 'i'); await updateDispDanmakus( manager.filtered.filter(d => regex.test(d.content)), { wordcloud: keyword } ); }); } else charts.wordcloud.clear(); const freq = {}; data.forEach(d => { d.content.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, ' ').split(/\s+/).forEach(w => { if (w.length >= 2) freq[w] = (freq[w] || 0) + 1; }); }); const list = Object.entries(freq).map(([name, value]) => ({ name, value })); charts.wordcloud.setOption({ title: { text: '弹幕词云' }, tooltip: {}, series: [{ type: 'wordCloud', gridSize: 8, sizeRange: [12, 40], rotationRange: [0, 0], shape: 'circle', data: list }] }); } function renderDensityChart(data) { const el = doc.getElementById('chart-density'); if (!el) return; if (!charts.density) { charts.density = ECHARTS.init(el); charts.density.on('click', function (params) { const targetTime = params.value[0] * 1000; const list = displayedDanmakus.value; if (!list.length) return; // 找到最接近的弹幕 index let closestIndex = 0; let minDiff = Math.abs(list[0].progress - targetTime); for (let i = 1; i < list.length; i++) { const diff = Math.abs(list[i].progress - targetTime); if (diff < minDiff) { closestIndex = i; minDiff = diff; } } // 使用 Element Plus 表格 ref 滚动到该行 nextTick(() => { const rows = doc.querySelectorAll('.el-table__body-wrapper tbody tr'); const row = rows?.[closestIndex]; if (row) { row.scrollIntoView({ behavior: 'smooth', block: 'center' }); const original = row.style.backgroundColor; row.style.transition = 'background-color 0.3s ease'; row.style.backgroundColor = '#ecf5ff'; setTimeout(() => { row.style.backgroundColor = original || ''; }, 1500); } }); }); } const duration = videoData.value.duration * 1000; // ms const minutes = duration / 1000 / 60; // 动态设置 bin 数量 let binCount = 100; if (minutes <= 10) binCount = 60; else if (minutes <= 30) binCount = 90; else if (minutes <= 60) binCount = 60; else binCount = 30; const bins = new Array(binCount).fill(0); data.forEach(d => { const idx = Math.floor((d.progress / duration) * binCount); bins[Math.min(idx, bins.length - 1)]++; }); const dataPoints = []; for (let i = 0; i < binCount; i++) { const timeSec = Math.floor((i * duration) / binCount / 1000); dataPoints.push({ value: [timeSec, bins[i]], name: formatProgress(timeSec * 1000) }); } charts.density.setOption({ title: { text: '弹幕密度分布' }, tooltip: { trigger: 'axis', formatter: function (params) { const sec = params[0].value[0]; return `时间段:${formatProgress(sec * 1000)}
弹幕数:${params[0].value[1]}`; }, axisPointer: { type: 'line' } }, xAxis: { type: 'value', name: '时间', min: 0, max: Math.ceil(duration / 1000), axisLabel: { formatter: val => formatProgress(val * 1000) } }, yAxis: { type: 'value', name: '弹幕数量' }, series: [{ data: dataPoints, type: 'line', smooth: true, areaStyle: {} // 可选加背景区域 }] }); } function renderDateChart(data) { const el = doc.getElementById('chart-date'); if (!el) return; if (!charts.date) { charts.date = ECHARTS.init(el); charts.date.on('click', async (params) => { const selectedDate = params.name; await updateDispDanmakus( manager.filtered.filter(d => formatTime(d.ctime).startsWith(selectedDate)), { date: selectedDate } ); }); } const countMap = {}; data.forEach(d => { const date = formatTime(d.ctime).split(' ')[0]; countMap[date] = (countMap[date] || 0) + 1; }); // 按日期升序排序 const sorted = Object.entries(countMap).sort((a, b) => new Date(a[0]) - new Date(b[0])); const x = sorted.map(([date]) => date); const y = sorted.map(([, count]) => count); const totalDays = x.length; const startIdx = Math.max(0, totalDays - 30); // 只显示最近30天 charts.date.setOption({ title: { text: '发送日期分布' }, tooltip: {}, xAxis: { type: 'category', data: x }, yAxis: { type: 'value', name: '弹幕数量' }, dataZoom: [ { type: 'slider', startValue: startIdx, endValue: totalDays - 1, xAxisIndex: 0, height: 20 } ], series: [{ type: 'bar', data: y }] }); } function renderHourChart(data) { const el = doc.getElementById('chart-hour'); if (!el) return; if (!charts.hour) { charts.hour = ECHARTS.init(el); charts.hour.on('click', async (params) => { const selectedHour = parseInt(params.name); await updateDispDanmakus( manager.filtered.filter(d => { const h = new Date(d.ctime * 1000).getHours(); return h === selectedHour; }), { hour: selectedHour } ); }); } const hours = new Array(24).fill(0); data.forEach(d => { const hour = new Date(d.ctime * 1000).getHours(); hours[hour]++; }); charts.hour.setOption({ title: { text: '发送时间分布' }, tooltip: {}, xAxis: { type: 'category', data: hours.map((_, i) => i + '时') }, yAxis: { type: 'value', name: '弹幕数量' }, series: [{ type: 'bar', data: hours }] }); } function updateChart() { const stats = manager.getStats(); danmakuCount.value = { user: stats.length, dm: displayedDanmakus.value.length }; renderUserChart(stats); renderDensityChart(manager.filtered); renderWordCloud(manager.filtered); renderDateChart(manager.filtered); renderHourChart(manager.filtered); } function handleRowClick(row) { if (!charts.user) return; let el = doc.getElementById('wrapper-chart'); if (!el) return; while (el && el !== doc.body) { //寻找可以滚动的父级元素 const overflowY = getComputedStyle(el).overflowY; const canScroll = overflowY === 'scroll' || overflowY === 'auto'; if (canScroll && el.scrollHeight > el.clientHeight) { el.scrollTo({ top: 0, behavior: 'smooth' }); break; } el = el.parentElement; } const userMid = row.midHash; const option = charts.user.getOption(); const sc = isExpandedUserChart.value ? 20 : 8; const scup = isExpandedUserChart.value ? 9 : 3; const index = option.yAxis[0].data.indexOf(userMid); if (index >= 0) { charts.user.setOption({ yAxis: { axisLabel: { formatter: function (value) { if (value === userMid) { return '{a|' + value + '}'; } else { return value; } }, rich: { a: { color: '#5470c6', fontWeight: 'bold' } } } }, dataZoom: [{ startValue: Math.min(option.yAxis[0].data.length - sc, Math.max(0, index - scup)), endValue: Math.min(option.yAxis[0].data.length - 1, Math.max(0, index - scup) + sc - 1) }] }); } } async function updateDispDanmakus(data, text, ifchart) { loading.value = true; await nextTick(); await new Promise(resolve => setTimeout(resolve, 10)); //等待v-loading渲染 try { displayedDanmakus.value = data; currentSubFilt.value = text; if (ifchart) { updateChart(); } await nextTick(); } catch (err) { console.error(err); ELEMENT_PLUS.ElMessage.error('数据显示错误'); } finally { loading.value = false; } } async function clearSubFilter() { await updateDispDanmakus(manager.filtered, {}); } async function applyFilter() { try { const regex = new RegExp(filterText.value, 'i'); manager.filter(regex); currentFilt.value = regex; await updateDispDanmakus(manager.filtered, {}, true); } catch (e) { console.warn(e); alert('无效正则表达式'); } } async function resetFilter() { manager.reset(); currentFilt.value = ''; await updateDispDanmakus(manager.filtered, {}, true); } onMounted(async () => { if (!dataParam?.videoData || !dataParam?.danmakuData || !Array.isArray(dataParam.danmakuData)) { ELEMENT_PLUS.ElMessageBox.alert( '初始化数据缺失,无法加载弹幕统计面板。请确认主页面传入了有效数据。', '错误', { type: 'error' } ); dataParam.danmakuData = []; } if (dataParam.videoData?.pic?.startsWith('http:')) { dataParam.videoData.pic = dataParam.videoData.pic.replace(/^http:/, 'https:'); } if (dataParam.videoData?.owner?.face?.startsWith('http:')) { dataParam.videoData.owner.face = dataParam.videoData.owner.face.replace(/^http:/, 'https:'); } if (dataParam.videoData.pages) { if (!isNaN(dataParam.p) && dataParam.videoData.pages[dataParam.p - 1]) { videoData.value.page_cur = dataParam.videoData.pages[dataParam.p - 1]; videoData.value.duration = videoData.value.page_cur.duration; } else if (dataParam.videoData.pages[0]) { videoData.value.duration = dataParam.videoData.pages[0].duration; } } manager = new DanmakuManager(dataParam.danmakuData); originDanmakuCount.value = manager.original.length; // 原始弹幕数量 await updateDispDanmakus(manager.filtered, {}, true); }); return { displayedDanmakus, filterText, applyFilter, resetFilter, videoData, danmakuCount, originDanmakuCount, currentFilt, currentSubFilt, loading, isExpandedUserChart, isTableVisible, isTableAutoH, panelInfo, visibleCharts, chartHover, moveChartUp, moveChartDown, moveChartOut, midHashOnClick, handleRowClick, clearSubFilter, formatProgress, formatCtime, formatTime, shareImage }; }, template: `

{{ videoData.title || '加载中...' }}
视频封面

第 {{ videoData.page_cur.page }} P:{{ videoData.page_cur.part }}

BVID: {{ videoData.bvid }}
UP主: {{ videoData.owner.name }}

UP主头像

发布时间: {{ videoData.pubdate ? formatTime(videoData.pubdate) : '-' }}
截止 {{ formatTime(Math.floor(Date.now()/1000)) }} 播放量: {{ videoData.stat.view || '-' }}
总弹幕数: {{ videoData.stat.danmaku || '-' }} ,载入实时弹幕 {{ originDanmakuCount }}

共有 {{ danmakuCount.user }} 位不同用户发送了 {{ danmakuCount.dm }} 条弹幕

弹幕列表
{{ isTableVisible ? '▲ 收起' : '▼ 展开' }}
` }); app.use(ELEMENT_PLUS); app.mount('#danmaku-app'); } // 获取数据 class BiliDanmakuUtils { constructor() { this.bvid = null; this.p = null; this.cid = null; this.videoData = null; this.danmakuData = null; this.danmakuXmlText = null; this.logStyle = { tag: 'Danmaku Statistic', style: 'background: #00a2d8; color: white; padding: 2px 6px; border-radius: 3px;', errorStyle: 'background: #ff4d4f; color: white; padding: 2px 6px; border-radius: 3px;' }; this.crcTable = null; } logTag(...args) { console.log(`%c${this.logStyle.tag}`, this.logStyle.style, ...args); } logTagError(...args) { console.error(`%c${this.logStyle.tag}`, this.logStyle.errorStyle, ...args); } parseDanmakuXml(xmlText) { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlText, 'application/xml'); const dElements = xmlDoc.getElementsByTagName('d'); const danmakus = []; for (const d of dElements) { const pAttr = d.getAttribute('p'); if (!pAttr) continue; const parts = pAttr.split(','); if (parts.length < 8) continue; danmakus.push({ progress: parseFloat(parts[0]) * 1000, mode: parseInt(parts[1]), fontsize: parseInt(parts[2]), color: parseInt(parts[3]), ctime: parseInt(parts[4]), pool: parseInt(parts[5]), midHash: parts[6], dmid: parts[7], weight: parseInt(parts[8]), content: d.textContent.trim() }); } this.logTag(`解析弹幕xml文本完成,共 ${danmakus.length} 条弹幕`); return danmakus; } parseBiliUrl(url) { this.bvid = null; this.p = null; const bvidMatch = url.match(/BV[a-zA-Z0-9]+/); if (bvidMatch) this.bvid = bvidMatch[0]; if (this.bvid) { const pMatch = url.match(/[?&]p=(\d+)/); if (pMatch) { const parsedP = parseInt(pMatch[1], 10); if (!isNaN(parsedP) && parsedP >= 1) { this.p = parsedP; } } if (this.p) { this.logTag(`解析 URL 得到 BVID=${this.bvid}, 分页p=${this.p}`); } else { this.logTag(`解析 URL 得到 BVID=${this.bvid}`); } } else { this.logTagError(`解析 URL=${url} 未找到 BVID`); } return { bvid: this.bvid, p: this.p }; } async getVideoData() { try { if (!this.bvid) throw new Error('BVID 缺失'); const res = await fetch(`https://api.bilibili.com/x/web-interface/view?bvid=${this.bvid}`); const json = await res.json(); if (json && json.data) { this.videoData = json.data; this.logTag('获取视频信息成功'); return this.videoData; } else throw new Error(`视频信息接口请求失败,json:${json}`); } catch (e) { this.logTagError('请求视频信息失败:', e); return null; } } async getDanmakuData() { try { this.cid = this.videoData.pages[this.p - 1]?.cid || this.videoData.cid; if (!this.cid) throw new Error('ChatID 缺失'); const res = await fetch(`https://api.bilibili.com/x/v1/dm/list.so?oid=${this.cid}`); if (!res.ok) throw new Error(`弹幕接口请求失败,状态码:${res.status}`); this.danmakuXmlText = await res.text(); this.danmakuData = this.parseDanmakuXml(this.danmakuXmlText); this.logTag('获取弹幕数据成功'); return this.danmakuData; } catch (err) { this.logTagError('获取弹幕数据失败:', err); return null; } } async fetchAllData(url) { this.parseBiliUrl(url); await this.getVideoData(); await this.getDanmakuData(); return { videoData: this.videoData, danmakuData: this.danmakuData }; } _createCRCTable() { const CRCPOLYNOMIAL = 0xEDB88320; const table = new Array(256); for (let i = 0; i < 256; ++i) { let c = i; for (let j = 0; j < 8; ++j) { c = (c & 1) ? (CRCPOLYNOMIAL ^ (c >>> 1)) : (c >>> 1); } table[i] = c >>> 0; } return table; } midToHash(mid) { if (!this.crcTable) { this.crcTable = this._createCRCTable(); } let crc = 0xFFFFFFFF; const input = mid.toString(); for (let i = 0; i < input.length; i++) { const byte = input.charCodeAt(i); crc = (crc >>> 8) ^ this.crcTable[(crc ^ byte) & 0xFF]; } return ((crc ^ 0xFFFFFFFF) >>> 0).toString(16); } } const dmUtils = new BiliDanmakuUtils(); // 插入按钮 function insertButton() { const btn = document.createElement('div'); btn.id = 'danmaku-stat-btn'; btn.innerHTML = ` 弹幕统计
`; btn.style.position = 'fixed'; btn.style.left = '-100px'; // 露出约20px图标 btn.style.bottom = '40px'; btn.style.zIndex = '9997'; btn.style.width = '120px'; btn.style.height = '40px'; btn.style.backgroundColor = 'transparent'; btn.style.color = '#00ace5'; btn.style.borderTopRightRadius = '20px'; btn.style.borderBottomRightRadius = '20px'; btn.style.cursor = 'pointer'; btn.style.fontSize = '16px'; btn.style.display = 'flex'; btn.style.alignItems = 'center'; btn.style.justifyContent = 'space-between'; btn.style.boxShadow = '0 0 5px rgba(0, 172, 229, 0.3)'; btn.style.transition = 'left 0.3s ease-in-out, background-color 0.2s ease-in-out'; btn.onmouseenter = () => { btn.style.left = '-10px'; btn.style.backgroundColor = 'rgba(255, 255, 255, 0.9)'; btn.style.border = '1px solid #00ace5'; }; btn.onmouseleave = () => { btn.style.left = '-100px'; btn.style.backgroundColor = 'transparent'; btn.style.border = 'none'; }; const match = location.href.match(/^https:\/\/space\.bilibili\.com\/(\d+)/);//动态页 if (!match) { btn.onclick = openPanel; } else { const mid = match[1]; btn.onclick = () => { const midHash = dmUtils.midToHash(mid); navigator.clipboard.writeText(midHash).then(() => { alert(`mid: ${mid}\n\nmidHash: ${midHash} (已复制到剪贴板)`); }).catch(() => { alert(`mid: ${mid}\n\nmidHash: ${midHash}`); }); }; } const style = document.createElement('style'); style.textContent = ` #danmaku-stat-btn .label { margin-left: 20px; white-space: nowrap; color: #00ace5; user-select: none; } #danmaku-stat-btn .icon-wrapper { display: flex; align-items: center; justify-content: center; margin-right: 8px; flex-shrink: 0; } `; document.head.appendChild(style); document.body.appendChild(btn); } // 打开iframe弹幕统计面板 function openPanel() { if (document.getElementById('danmaku-stat-iframe')) { console.warn('统计面板已打开'); return; } // 创建蒙层 const overlay = document.createElement('div'); overlay.id = 'danmaku-stat-overlay'; overlay.style.position = 'fixed'; overlay.style.top = '0'; overlay.style.left = '0'; overlay.style.width = '100%'; overlay.style.height = '100%'; overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)'; overlay.style.zIndex = '9998'; overlay.onclick = () => { document.getElementById('danmaku-stat-iframe')?.remove(); overlay.remove(); }; document.body.appendChild(overlay); // 创建iframe const iframe = document.createElement('iframe'); iframe.id = 'danmaku-stat-iframe'; iframe.style.position = 'fixed'; iframe.style.top = '15%'; iframe.style.left = '15%'; iframe.style.width = '70%'; iframe.style.height = '70%'; iframe.style.backgroundColor = '#fff'; iframe.style.zIndex = '9999'; iframe.style.padding = '20px'; iframe.style.overflow = 'hidden'; iframe.style.borderRadius = '8px'; iframe.style.boxShadow = '0 0 10px rgba(0,0,0,0.5)'; iframe.onload = async () => { try { await dmUtils.fetchAllData(location.href); initIframeApp(iframe, dmUtils, { type: 0, newPanel: function (type) { if (type == 0) { openPanelInNewTab(); dmUtils.logTag('[主页面] 新建子页面'); } } }); } catch (err) { dmUtils.logTagError('初始化失败:', err); alert(`弹幕统计加载失败:${err.message}`); } }; document.body.appendChild(iframe); } // 打开新标签页弹幕统计面板 function openPanelInNewTab() { const htmlContent = ` Bilibili 弹幕统计 `; const blob = new Blob([htmlContent], { type: 'text/html' }); const blobUrl = URL.createObjectURL(blob); const newWin = window.open(blobUrl, '_blank'); if (!newWin) { alert('浏览器阻止了弹出窗口'); return; } } // 保存弹幕统计面板 function savePanel() { const htmlContent = ` Bilibili 弹幕统计 `; const blob = new Blob([htmlContent], { type: 'text/html' }); const blobUrl = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = blobUrl; link.download = `${dmUtils.bvid}_danmaku_statistics.html`; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(blobUrl); } // 监听新标签页消息 window.addEventListener('message', (event) => { if (event.data?.type === 'DMSTATS_REQUEST_DATA') { dmUtils.logTag('[主页面] 收到数据请求'); event.source.postMessage(dmUtils, '*'); } else if (event.data?.type === 'DMSTATS_REQUEST_SAFE') { dmUtils.logTag('[主页面] 收到保存请求'); savePanel(); } }); insertButton(); })();