Skip to content

Instantly share code, notes, and snippets.

@blackgear
Last active February 10, 2022 11:33
Show Gist options
  • Save blackgear/c7c224d2e09e20175cb2a0a03cda7db0 to your computer and use it in GitHub Desktop.
Save blackgear/c7c224d2e09e20175cb2a0a03cda7db0 to your computer and use it in GitHub Desktop.
点击一下即可开启中英双字幕,适用于YouTube™,改编自https://github.com/ADengrc/youtube-captions/
// ==UserScript==
// @license MIT License
// @name YouTube™双字幕
// @description 点击一下即可开启中英双字幕,适用于YouTube™
// @namespace https://github.com/ADengrc/youtube-captions/
// @version 0.1.0
// @author Dengrc (Adopted by Daniel.Zeng)
// @match https://www.youtube.com/*
// @require https://cdn.jsdelivr.net/npm/xhook@latest/dist/xhook.min.js
// @grant none
// ==/UserScript==
(function() {
'use strict';
xhook.after(function (request, response) {
let url = request.url
if (url.includes('/api/timedtext')) {
const zhReg = /^zh-\w+/
const params = new URLSearchParams(url)
let lang = (params.get('lang') || '').toLocaleLowerCase()
let tlang = (params.get('tlang') || '').toLocaleLowerCase()
if (!zhReg.test(lang) && !zhReg.test(tlang)) {
let userLang
try {
JSON.parse(ytplayer.config.args.player_response).captions.playerCaptionsTracklistRenderer.captionTracks.forEach(lang => {
lang.languageCode = lang.languageCode.toLocaleLowerCase()
if (userLang && userLang.languageCode == 'zh-cn') return
if (zhReg.test(lang.languageCode)) {
lang.baseUrl += '&fmt=srv3'
userLang = lang
}
})
} catch (error) {
console.log(error)
}
let xhr = new XMLHttpRequest();
xhr.open('GET', userLang ? userLang.baseUrl : `${url}&tlang=zh-Hans`, false);
xhr.send();
xhr.responseXML.querySelectorAll('p').forEach(e => {
let p = response.xml.querySelector(`p[t='${e.getAttribute('t')}']`);
if (p) {
if (p.childElementCount && e.previousElementSibling) {
let previous = e.previousElementSibling;
previous.setAttribute('d', e.getAttribute('t') - previous.getAttribute('t'));
}
e.textContent = [p.textContent.replace('\n', ' '), e.textContent.replace('\n', ' ')].join('\n');
}
});
response.text = new XMLSerializer().serializeToString(xhr.responseXML);
}
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment