Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jim60105/9515346675ebc27b06ccc8f058d9da65 to your computer and use it in GitHub Desktop.
Save jim60105/9515346675ebc27b06ccc8f058d9da65 to your computer and use it in GitHub Desktop.
Youtube: 觀看5分鐘影片後自動按喜歡
// ==UserScript==
// @name Youtube: Automatically press like after watching 5 minutes of video
// @name:zh Youtube: 觀看5分鐘影片後自動按喜歡
// @version 1.1.3
// @description Youtube: Automatically press like after watching 5 minutes of video
// @author 琳(jim60105)
// @match https://www.youtube.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=youtube.com
// @license GPL3
// ==/UserScript==
(function () {
'use strict';
/**
* @type {number} waitForSeconds - The number of seconds to wait before pressing the button.
*/
const waitForSeconds = 5 * 60;
/////////////////////////// DO NOT TOUCH ANYTHING BELOW THIS LINE ///////////////////////////
let timeout;
window.addEventListener('load', function () {
// Youtube doesn't refresh the page when you switch videos within the site.
DoWhenUrlChange(function () {
if (!CheckUrl()) return;
WaitAndPressTheButton();
});
});
function DoWhenUrlChange(func) {
// Youtube refreshes this element when you click on a link between homepage and video page.
const headerElement = document.getElementById('masthead');
// Youtube refreshes this element when you click on a link and jump BETWEEN video pages.
let videoElement;
// Init with empty string so that the first time the page loads, the function will be executed.
let previousUrl = '';
const config = { attributes: true, childList: false, characterData: false };
const observer = new MutationObserver(function (mutations) {
if (location.href !== previousUrl) {
previousUrl = location.href;
// console.log(`URL changed to ${location.href}`);
func();
// The video element is not available when entering from the home page.
if (!videoElement) {
videoElement = document.getElementsByTagName('video')[0];
if (videoElement) {
observer.observe(videoElement, config);
}
}
}
});
if (headerElement) observer.observe(headerElement, config);
}
function CheckUrl() {
return window.location.pathname.match('^/watch');
}
function WaitAndPressTheButton() {
console.log(`Automatically press like button after waiting ${waitForSeconds} seconds...`);
clearTimeout(timeout);
timeout = setTimeout(function () {
const buttonTags = document.getElementsByTagName('like-button-view-model');
Array.from(buttonTags).forEach((tags) => {
const button = tags.getElementsByTagName('button')[0];
if (button.getAttribute('aria-pressed') === 'true') return;
button.click();
console.log('Automatically liked this video!');
});
}, waitForSeconds * 1000);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment