Skip to content

Instantly share code, notes, and snippets.

@qwertyuiop6
Last active September 15, 2024 05:32
Show Gist options
  • Save qwertyuiop6/8499fe086491da90617fe17c32716d4e to your computer and use it in GitHub Desktop.
Save qwertyuiop6/8499fe086491da90617fe17c32716d4e to your computer and use it in GitHub Desktop.
🌍 🪄 🀄 Translate to Chinese automatically. Youtube自动点击翻译字幕到中文简体
// ==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();
}
})();
@Gilgamesh-lzq
Copy link

如果没有成功有可能是你的youtube设置是英文的 需要把你的界面设置为中文,因为代码的逻辑是通过找到“字幕” 这样的按钮去点击,如果你的界面设置是英文的话 就找不到这个按钮。我个人是这个原因
设置中文界面的方法 https://acc15t4bm5.feishu.cn/docs/doccn66lNAP0P0zZrSK0YLQ5HWh

设置中文界面会被推很多政治方面恶心人的视频,切英文界面再也没出现过。改代码大概也可以吧,无非是把按钮改成英文

@Kira0v0
Copy link

Kira0v0 commented May 25, 2023

油管没有设置默认字幕就离谱,只能找脚本用了,这个真好用

@Gilgamesh-lzq
Copy link

Gilgamesh-lzq commented May 25, 2023 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment