// ==UserScript== // @name Bilibili MediaSession Helper // @namespace http://tampermonkey.net/ // @version 0.4 // @description Dock metadata to MediaSession API for bilibili.com (Chrome 73+) // @author nondanee // @match https://*.bilibili.com/* // @grant none // @downloadURL none // ==/UserScript== (() => { if (!('mediaSession' in navigator)) return if (self != top) return const updateMetadata = inital => Promise.resolve() .then(() => { const url = window.location.href let id, title, artist, cover if (id = (url.match(/live\.bilibili\.com\/(\d+)/) || [])[1]) { return fetch(`//api.live.bilibili.com/xlive/web-room/v1/index/getInfoByRoom?room_id=${id}`) .then(response => response.json()) .then(body => body.data) .then(data => Object.assign(data.room_info, {artist: data.anchor_info.base_info.uname})) } else if (id = (url.match(/bilibili\.com\/video\/av(\d+)/) || [])[1]) { const {videoData} = window.__INITIAL_STATE__ return { title: videoData.title, artist: videoData.owner.name, cover: videoData.pic.replace('https:', '').replace('http:', '') } } else if (id = (url.match(/bilibili\.com\/bangumi\/play\/\D+(\d+)/) || [])[1]) { const {progress} = window.__PGC_USERSTATE__ const {epList, mediaInfo} = window.__INITIAL_STATE__ const epInfo = (epList || []).find(item => (item.id === progress.last_ep_id && inital) || item.id.toString() === id) || window.__INITIAL_STATE__.epInfo return { title: mediaInfo.title, artist: (epInfo.titleFormat + ' ' + epInfo.longTitle).trim(), cover: epInfo.cover } } }) .then(({title, artist, cover}) => { const image = new Image() image.onload = () => { navigator.mediaSession.metadata = new window.MediaMetadata({ title, artist, artwork: [{src: cover, sizes: `${image.naturalWidth}x${image.naturalHeight}`, type: 'image/jpeg'}] }) } image.src = cover }) updateMetadata(true) const _pushState = history.pushState history.pushState = function (...props) { _pushState.apply(this, props) updateMetadata() } const _replaceState = history.replaceState history.replaceState = function (...props) { _replaceState.apply(this, props) updateMetadata() } })()