Forked from qwertyuiop6/TranslateToChineseOnYouTube.user.js
Created
April 11, 2022 12:03
-
-
Save sahwar/82e0922630a9b8ea09f69466defc87a9 to your computer and use it in GitHub Desktop.
Translate to Chinese automatically. youtube自动翻译中文简体
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name YouTube字幕自动选择翻译->中文简体 | |
// @namespace http://tampermonkey.net/ | |
// @version 1.2 | |
// @description translate to Chinese automatically. 自动点击字幕翻译到中文简体 | |
// @author qwertyuiop6 | |
// @match https://www.youtube.com/* | |
// @grant none | |
// ==/UserScript== | |
(function(){ | |
const $=document.querySelector.bind(document); | |
const $$=document.getElementsByClassName.bind(document); | |
let video; | |
if(!location.href.includes('watch')){ | |
document.addEventListener('click',e=>{ | |
console.log(e.target) | |
if(e.target.closest('.ytd-rich-grid-media')){ | |
setTimeout(listenVideo,300) | |
} | |
},true) | |
}else{ | |
listenVideo() | |
} | |
function listenVideo(){ | |
video=$('video'); | |
video.addEventListener('canplay', ()=>{ | |
$('.ytp-ad-skip-button-icon')?.click(); | |
}) | |
video.addEventListener('loadeddata',clickToTranslate) | |
} | |
function checkAndClick(){ | |
const findElem=findElemByText.bind($$("ytp-menuitem")) | |
const sub=findElem("字幕"); | |
if (!sub) return false; | |
sub.click(); | |
const subc = findElem("中文"); | |
if (subc) { | |
subc.click(); | |
video.click(); | |
} else { | |
const autoTrans = findElem("自动翻译"); | |
if (!autoTrans) return false; | |
autoTrans.click(); | |
const autoTransC = findElem("中文(简体)"); | |
if (!autoTransC) return false; | |
autoTransC.click(); | |
} | |
return true; | |
} | |
function findElemByText(text) { | |
for (const elem of this) { | |
if (elem.innerText.includes(text)) { | |
return elem | |
} | |
} | |
return null | |
} | |
function clickToTranslate(){ | |
$('.ytp-subtitles-button[aria-pressed="false"]')?.click(); | |
const settingsButton=$('.ytp-settings-button'); | |
settingsButton.click(); | |
if(!checkAndClick()) settingsButton.click(); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment