// ==UserScript== // @name Youtube Subtitle Downloader v30 // @include https://*youtube.com/* // @author Cheng Zheng // @copyright 2009 Tim Smart; 2011 gw111zz; 2014~2021 Cheng Zheng; // @license GNU GPL v3.0 or later. http://www.gnu.org/copyleft/gpl.html // @require https://code.jquery.com/jquery-1.12.4.min.js // @version 30 // @grant GM_xmlhttpRequest // @namespace https://greasyfork.org/users/5711 // @description Download Subtitles // @downloadURL none // ==/UserScript== /* [What is this?] This Tampermonkey script allows you to download Youtube "Automatic subtitle" and "closed subtitle". [Note] If it doesn't work (rarely), try to refresh the page. If problem still exists after refreshing, send an email to guokrfans@gmail.com. [Who built this?] Author : Cheng Zheng (郑诚) Email : guokrfans@gmail.com Github : https://github.com/1c7/Youtube-Auto-Subtitle-Download If you want to improve the script, Github pull requests are welcome. [Note for Developers] Few things before you read the code: 0. Some comments are written in Chinese. 1. Youtube has 2 interfaces: Material Design and The Old Design. 2. This code handles both "Auto" and "Closed" subtitles. [What is "Tampermonkey"?] "Tampermonkey script" means that you needs to install a browser extension called "Tampermonkey" before installing this script. Tempermonkey is available for most modern web browsers, such as Chrome, Firefox, Safari, Microsoft Edge, and Opera. [Test Video] https://www.youtube.com/watch?v=bkVsus8Ehxs This videos only has a closed English subtitle, with no auto subtitles. https://www.youtube.com/watch?v=-WEqFzyrbbs no subtitle at all https://www.youtube.com/watch?v=9AzNEG1GB-k have a lot of subtitles https://www.youtube.com/watch?v=tqGkOvrKGfY 1:36:33 super long subtitle [How does it work?] The code can be roughly divided into three parts: 1. Add a button on the page. (UI) 2. Detect if subtitle exists. 3. Convert subtitle format, then download. [Test Enviroment] Works best on Chrome + Tampermonkey. There are plenty Chromium-based Browser, I do not guarantee this work on all of them; 个别情况下不能用是因为 jQuery 的 CDN 无法载入,解决办法是修改这一行 // @require https://code.jquery.com/jquery-1.12.4.min.js 改成一个别的 jQuery 地址,比如 https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.js https://cdn.staticfile.org/jquery/1.12.4/jquery.min.js */ (function () { // Config var NO_SUBTITLE = 'No Subtitle'; var HAVE_SUBTITLE = 'Download Subtitles'; var TEXT_LOADING = 'Loading...'; const BUTTON_ID = 'youtube-subtitle-downloader-by-1c7-last-update-2021-2-21' // Config var HASH_BUTTON_ID = `#${BUTTON_ID}` // initialize var first_load = true; // indicate if first load this webpage or not var youtube_playerResponse_1c7 = null; // for auto subtitle unsafeWindow.caption_array = []; // store all subtitle // trigger when first load $(document).ready(function () { start(); }); // Explain this function: we repeatly try if certain HTML element exist, // if it does, we call init() // if it doesn't, stop trying after certain time function start() { var retry_count = 0; var RETRY_LIMIT = 30; // use "setInterval" is because "$(document).ready()" still not enough, still too early // 330 work for me. if (new_material_design_version()) { var material_checkExist = setInterval(function () { if (document.querySelectorAll('.title.style-scope.ytd-video-primary-info-renderer').length) { init(); clearInterval(material_checkExist); } retry_count = retry_count + 1; if (retry_count > RETRY_LIMIT) { clearInterval(material_checkExist); } }, 330); } else { var checkExist = setInterval(function () { if ($('#watch7-headline').length) { init(); clearInterval(checkExist); } retry_count = retry_count + 1; if (retry_count > RETRY_LIMIT) { clearInterval(checkExist); } }, 330); } } // trigger when loading new page // (actually this would also trigger when first loading, that's not what we want, that's why we need to use firsr_load === false) // (new Material design version would trigger this "yt-navigate-finish" event. old version would not.) var body = document.getElementsByTagName("body")[0]; body.addEventListener("yt-navigate-finish", function (event) { // 2021-8-9 测试结果:yt-navigate-finish 可以正常触发 if (current_page_is_video_page() === false) { return; } youtube_playerResponse_1c7 = event.detail.response.playerResponse; // for auto subtitle unsafeWindow.caption_array = []; // clean up (important, otherwise would have more and more item and cause error) // if use click to another page, init again to get correct subtitle if (first_load === false) { remove_subtitle_download_button(); init(); } }); // return true / false // Detect [new version UI(material design)] OR [old version UI] // I tested this, accurated. function new_material_design_version() { var old_title_element = document.getElementById('watch7-headline'); if (old_title_element) { return false; } else { return true; } } // return true / false function current_page_is_video_page() { return get_url_video_id() !== null; } // return string like "RW1ChiWyiZQ", from "https://www.youtube.com/watch?v=RW1ChiWyiZQ" // or null function get_url_video_id() { return getURLParameter('v'); } //https://stackoverflow.com/questions/11582512/how-to-get-url-parameters-with-javascript/11582513#11582513 function getURLParameter(name) { return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null; } function remove_subtitle_download_button() { $(HASH_BUTTON_ID).remove(); } function init() { inject_our_script(); first_load = false; } function inject_our_script() { var div = document.createElement('div'), select = document.createElement('select'), option = document.createElement('option'), controls = document.getElementById('watch7-headline'); // Youtube video title DIV var css_div = `display: table; margin-top:4px; border: 1px solid rgb(0, 183, 90); cursor: pointer; color: rgb(255, 255, 255); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; background-color: #00B75A; `; div.setAttribute('style', css_div); div.id = BUTTON_ID; select.id = 'captions_selector'; select.disabled = true; let css_select = `display:block; border: 1px solid rgb(0, 183, 90); cursor: pointer; color: rgb(255, 255, 255); background-color: #00B75A; padding: 4px; `; select.setAttribute('style', css_select); option.textContent = TEXT_LOADING; option.selected = true; select.appendChild(option); // 下拉菜单里,选择一项后触发下载 select.addEventListener('change', function () { download_subtitle(this); }, false); div.appendChild(select); // put async function load_language_list(select) { // auto var auto_subtitle_exist = false; // closed var closed_subtitle_exist = false; var captions = null; // get auto subtitle var auto_subtitle_url = get_auto_subtitle_xml_url(); if (auto_subtitle_url != false) { auto_subtitle_exist = true; } // does closed subtitle exists? var tracks_xml_string = await get_closed_subtitles(); captions = new DOMParser().parseFromString(tracks_xml_string, "text/xml").getElementsByTagName('track'); if (captions.length != 0) { closed_subtitle_exist = true; } // if no subtitle at all, just say no and stop if (auto_subtitle_exist == false && closed_subtitle_exist == false) { select.options[0].textContent = NO_SUBTITLE; disable_download_button(); return false; } // if at least one type of subtitle exist select.options[0].textContent = HAVE_SUBTITLE; select.disabled = false; var caption = null; // for inside loop var option = null; // for