b站显示视频 av 号、bv 号及弹幕 cid

在b站播放页标题栏下面显示视频 av 号、bv 号及弹幕 cid

目前為 2020-05-21 提交的版本,檢視 最新版本

// ==UserScript==
// @name                b站显示视频 av 号、bv 号及弹幕 cid
// @namespace           https://gist.github.com/phtwo
// @version             0.1.2
// @description         在b站播放页标题栏下面显示视频 av 号、bv 号及弹幕 cid
// @match               *://www.bilibili.com/video/av*
// @match               *://www.bilibili.com/video/BV*
// @grant               none
//
// @author              phtwo
// @homepage            https://gist.github.com/phtwo/e2d8c04707ed6a6369a55be37e3f14c7
// @supportURL          https://gist.github.com/phtwo/e2d8c04707ed6a6369a55be37e3f14c7
//
// @noframes
// @nocompat Chrome
//
// ==/UserScript==

(function () {
  const list = []

  /** @type Element */
  let videoDataLineElem

  init()

  function init() {
    console.log('bilibili_extra_video_data init')

    initVideoDataLineElem()
    if (!videoDataLineElem) {
      return
    }

    initMonitor()
  }

  function initVideoDataLineElem() {
    videoDataLineElem = document.querySelector('#viewbox_report .video-data:nth-of-type(2)')
  }

  function initMonitor() {
    const observer = new MutationObserver(mutations => {
      for (const mutation of mutations) {
        if ('attributes' === mutation.type) {
          observer.takeRecords()
          run()
          break
        }
      }
    })

    observer.observe(videoDataLineElem.children[0], {
      attributes: true,
      attributeFilter: ['title'],
    })
  }

  function run() {
    const {aid, bvid, cid} = window

    list.length = 0 // clear list
    addItem('av', aid)
    addItem('', bvid)
    addItem('cid', cid)

    const fragment = createFragment()

    const referenceNode = videoDataLineElem.querySelector('.copyright')
    removeOldNodes()
    videoDataLineElem.insertBefore(fragment, referenceNode)

    console.log('bilibili_extra_video_data run finished')
  }

  function createFragment() {
    const firstPrefix = '  '
    const prefix = ' · '

    const nodeList = list.map((item, index) => {
      let text = item.prefix + item.value
      let innerHTML = (index === 0 ? firstPrefix : prefix) + text

      const elem = document.createElement('span')
      elem.title = text
      elem.innerHTML = innerHTML
      elem.style.color = '#afafaf'
      elem.setAttribute('data-inject', 'injected')

      return elem
    })

    const fragment = document.createDocumentFragment()
    fragment.append(...nodeList)
    return fragment
  }

  function removeOldNodes() {
    videoDataLineElem
      .querySelectorAll('[data-inject]')
      .forEach(node => node.parentNode.removeChild(node))
  }

  function addItem(prefix = '', value) {
    value && list.push({prefix, value})
  }

})()