Return Youtube Dislike.user.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. // ==UserScript==
  2. // @name Return YouTube Dislike
  3. // @namespace https://www.returnyoutubedislike.com/
  4. // @homepage https://www.returnyoutubedislike.com/
  5. // @version 0.9.0
  6. // @encoding utf-8
  7. // @description Return of the YouTube Dislike, Based off https://www.returnyoutubedislike.com/
  8. // @icon https://github.com/Anarios/return-youtube-dislike/raw/main/Icons/Return%20Youtube%20Dislike%20-%20Transparent.png
  9. // @author Anarios & JRWR
  10. // @match *://*.youtube.com/*
  11. // @exclude *://music.youtube.com/*
  12. // @exclude *://*.music.youtube.com/*
  13. // @compatible chrome
  14. // @compatible firefox
  15. // @compatible opera
  16. // @compatible safari
  17. // @compatible edge
  18. // @downloadURL https://github.com/Anarios/return-youtube-dislike/raw/main/Extensions/UserScript/Return%20Youtube%20Dislike.user.js
  19. // @updateURL https://github.com/Anarios/return-youtube-dislike/raw/main/Extensions/UserScript/Return%20Youtube%20Dislike.user.js
  20. // @grant GM.xmlHttpRequest
  21. // @connect youtube.com
  22. // @grant GM_addStyle
  23. // @run-at document-end
  24. // ==/UserScript==
  25. const extConfig = {
  26. // BEGIN USER OPTIONS
  27. // You may change the following variables to allowed values listed in the corresponding brackets (* means default). Keep the style and keywords intact.
  28. showUpdatePopup: false, // [true, false*] Show a popup tab after extension update (See what's new)
  29. disableVoteSubmission: false, // [true, false*] Disable like/dislike submission (Stops counting your likes and dislikes)
  30. coloredThumbs: false, // [true, false*] Colorize thumbs (Use custom colors for thumb icons)
  31. coloredBar: false, // [true, false*] Colorize ratio bar (Use custom colors for ratio bar)
  32. colorTheme: "classic", // [classic*, accessible, neon] Color theme (red/green, blue/yellow, pink/cyan)
  33. numberDisplayFormat: "compactShort", // [compactShort*, compactLong, standard] Number format (For non-English locale users, you may be able to improve appearance with a different option. Please file a feature request if your locale is not covered)
  34. numberDisplayRoundDown: true, // [true*, false] Round down numbers (Show rounded down numbers)
  35. // END USER OPTIONS
  36. };
  37. const LIKED_STATE = "LIKED_STATE";
  38. const DISLIKED_STATE = "DISLIKED_STATE";
  39. const NEUTRAL_STATE = "NEUTRAL_STATE";
  40. let previousState = 3; //1=LIKED, 2=DISLIKED, 3=NEUTRAL
  41. let likesvalue = 0;
  42. let dislikesvalue = 0;
  43. let isMobile = location.hostname == "m.youtube.com";
  44. let isShorts = () => location.pathname.startsWith("/shorts");
  45. let mobileDislikes = 0;
  46. function cLog(text, subtext = "") {
  47. subtext = subtext.trim() === "" ? "" : `(${subtext})`;
  48. console.log(`[Return YouTube Dislikes] ${text} ${subtext}`);
  49. }
  50. function isInViewport(element) {
  51. const rect = element.getBoundingClientRect();
  52. const height = innerHeight || document.documentElement.clientHeight;
  53. const width = innerWidth || document.documentElement.clientWidth;
  54. return (
  55. rect.top >= 0 &&
  56. rect.left >= 0 &&
  57. rect.bottom <= height &&
  58. rect.right <= width
  59. );
  60. }
  61. function getButtons() {
  62. if (isShorts()) {
  63. let elements = document.querySelectorAll(
  64. isMobile
  65. ? "ytm-like-button-renderer"
  66. : "#like-button > ytd-like-button-renderer"
  67. );
  68. for (let element of elements) {
  69. if (isInViewport(element)) {
  70. return element;
  71. }
  72. }
  73. }
  74. if (isMobile) {
  75. return document.querySelector(".slim-video-action-bar-actions");
  76. }
  77. if (document.getElementById("menu-container")?.offsetParent === null) {
  78. return document.querySelector("ytd-menu-renderer.ytd-watch-metadata > div");
  79. } else {
  80. return document
  81. .getElementById("menu-container")
  82. ?.querySelector("#top-level-buttons-computed");
  83. }
  84. }
  85. function getLikeButton() {
  86. return getButtons().children[0];
  87. }
  88. function getDislikeButton() {
  89. return getButtons().children[1];
  90. }
  91. let mutationObserver = new Object();
  92. if (isShorts() && mutationObserver.exists !== true) {
  93. cLog('initializing mutation observer')
  94. mutationObserver.options = {
  95. childList: false,
  96. attributes: true,
  97. subtree: false
  98. };
  99. mutationObserver.exists = true;
  100. mutationObserver.observer = new MutationObserver( function(mutationList, observer) {
  101. mutationList.forEach( (mutation) => {
  102. if (mutation.type === 'attributes' &&
  103. mutation.target.nodeName === 'TP-YT-PAPER-BUTTON' &&
  104. mutation.target.id === 'button') {
  105. cLog('Short thumb button status changed');
  106. if (mutation.target.getAttribute('aria-pressed') === 'true') {
  107. mutation.target.style.color =
  108. (mutation.target.parentElement.parentElement.id === 'like-button') ?
  109. getColorFromTheme(true) : getColorFromTheme(false);
  110. } else {
  111. mutation.target.style.color = 'unset';
  112. }
  113. return;
  114. }
  115. cLog('unexpected mutation observer event: ' + mutation.target + mutation.type);
  116. });
  117. });
  118. }
  119. function isVideoLiked() {
  120. if (isMobile) {
  121. return (
  122. getLikeButton().querySelector("button").getAttribute("aria-label") ==
  123. "true"
  124. );
  125. }
  126. return getLikeButton().classList.contains("style-default-active");
  127. }
  128. function isVideoDisliked() {
  129. if (isMobile) {
  130. return (
  131. getDislikeButton().querySelector("button").getAttribute("aria-label") ==
  132. "true"
  133. );
  134. }
  135. return getDislikeButton().classList.contains("style-default-active");
  136. }
  137. function isVideoNotLiked() {
  138. if (isMobile) {
  139. return !isVideoLiked();
  140. }
  141. return getLikeButton().classList.contains("style-text");
  142. }
  143. function isVideoNotDisliked() {
  144. if (isMobile) {
  145. return !isVideoDisliked();
  146. }
  147. return getDislikeButton().classList.contains("style-text");
  148. }
  149. function checkForUserAvatarButton() {
  150. if (isMobile) {
  151. return;
  152. }
  153. if (document.querySelector("#avatar-btn")) {
  154. return true;
  155. } else {
  156. return false;
  157. }
  158. }
  159. function getState() {
  160. if (isVideoLiked()) {
  161. return LIKED_STATE;
  162. }
  163. if (isVideoDisliked()) {
  164. return DISLIKED_STATE;
  165. }
  166. return NEUTRAL_STATE;
  167. }
  168. function setLikes(likesCount) {
  169. if (isMobile) {
  170. getButtons().children[0].querySelector(".button-renderer-text").innerText =
  171. likesCount;
  172. return;
  173. }
  174. getButtons().children[0].querySelector("#text").innerText = likesCount;
  175. }
  176. function setDislikes(dislikesCount) {
  177. if (isMobile) {
  178. mobileDislikes = dislikesCount;
  179. return;
  180. }
  181. getButtons().children[1].querySelector("#text").innerText = dislikesCount;
  182. }
  183. (typeof GM_addStyle != "undefined"
  184. ? GM_addStyle
  185. : (styles) => {
  186. let styleNode = document.createElement("style");
  187. styleNode.type = "text/css";
  188. styleNode.innerText = styles;
  189. document.head.appendChild(styleNode);
  190. })(`
  191. #return-youtube-dislike-bar-container {
  192. background: var(--yt-spec-icon-disabled);
  193. border-radius: 2px;
  194. }
  195. #return-youtube-dislike-bar {
  196. background: var(--yt-spec-text-primary);
  197. border-radius: 2px;
  198. transition: all 0.15s ease-in-out;
  199. }
  200. .ryd-tooltip {
  201. position: relative;
  202. display: block;
  203. height: 2px;
  204. top: 9px;
  205. }
  206. .ryd-tooltip-bar-container {
  207. width: 100%;
  208. height: 2px;
  209. position: absolute;
  210. padding-top: 6px;
  211. padding-bottom: 28px;
  212. top: -6px;
  213. }
  214. `);
  215. function createRateBar(likes, dislikes) {
  216. if (isMobile) {
  217. return;
  218. }
  219. let rateBar = document.getElementById("return-youtube-dislike-bar-container");
  220. const widthPx =
  221. getButtons().children[0].clientWidth +
  222. getButtons().children[1].clientWidth +
  223. 8;
  224. const widthPercent =
  225. likes + dislikes > 0 ? (likes / (likes + dislikes)) * 100 : 50;
  226. if (!rateBar && !isMobile) {
  227. let colorLikeStyle = "";
  228. let colorDislikeStyle = "";
  229. if (extConfig.coloredBar) {
  230. colorLikeStyle = "; background-color: " + getColorFromTheme(true);
  231. colorDislikeStyle = "; background-color: " + getColorFromTheme(false);
  232. }
  233. document.getElementById("menu-container").insertAdjacentHTML(
  234. "beforeend",
  235. `
  236. <div class="ryd-tooltip" style="width: ${widthPx}px">
  237. <div class="ryd-tooltip-bar-container">
  238. <div
  239. id="return-youtube-dislike-bar-container"
  240. style="width: 100%; height: 2px;${colorDislikeStyle}"
  241. >
  242. <div
  243. id="return-youtube-dislike-bar"
  244. style="width: ${widthPercent}%; height: 100%${colorDislikeStyle}"
  245. ></div>
  246. </div>
  247. </div>
  248. <tp-yt-paper-tooltip position="top" id="ryd-dislike-tooltip" class="style-scope ytd-sentiment-bar-renderer" role="tooltip" tabindex="-1">
  249. <!--css-build:shady-->${likes.toLocaleString()}&nbsp;/&nbsp;${dislikes.toLocaleString()}
  250. </tp-yt-paper-tooltip>
  251. </div>
  252. `
  253. );
  254. } else {
  255. document.getElementById(
  256. "return-youtube-dislike-bar-container"
  257. ).style.width = widthPx + "px";
  258. document.getElementById("return-youtube-dislike-bar").style.width =
  259. widthPercent + "%";
  260. document.querySelector(
  261. "#ryd-dislike-tooltip > #tooltip"
  262. ).innerHTML = `${likes.toLocaleString()}&nbsp;/&nbsp;${dislikes.toLocaleString()}`;
  263. if (extConfig.coloredBar) {
  264. document.getElementById("return-youtube-dislike-bar-container").style.backgroundColor =
  265. getColorFromTheme(false);
  266. document.getElementById("return-youtube-dislike-bar").style.backgroundColor =
  267. getColorFromTheme(true);
  268. }
  269. }
  270. }
  271. function setState() {
  272. cLog("Fetching votes...");
  273. let statsSet = false;
  274. fetch(
  275. `https://returnyoutubedislikeapi.com/votes?videoId=${getVideoId()}`
  276. ).then((response) => {
  277. response.json().then((json) => {
  278. if (json && !("traceId" in response) && !statsSet) {
  279. const { dislikes, likes } = json;
  280. cLog(`Received count: ${dislikes}`);
  281. likesvalue = likes;
  282. dislikesvalue = dislikes;
  283. setDislikes(numberFormat(dislikes));
  284. createRateBar(likes, dislikes);
  285. if (extConfig.coloredThumbs === true) {
  286. if (isShorts()) { // for shorts, leave deactived buttons in default color
  287. let shortLikeButton = getLikeButton().querySelector('tp-yt-paper-button#button');
  288. let shortDislikeButton = getDislikeButton().querySelector('tp-yt-paper-button#button');
  289. if (shortLikeButton.getAttribute('aria-pressed') === 'true') {
  290. shortLikeButton.style.color = getColorFromTheme(true);
  291. }
  292. if (shortDislikeButton.getAttribute('aria-pressed') === 'true') {
  293. shortDislikeButton.style.color = getColorFromTheme(false);
  294. }
  295. mutationObserver.observer.observe(shortLikeButton, mutationObserver.options);
  296. mutationObserver.observer.observe(shortDislikeButton, mutationObserver.options);
  297. } else {
  298. getLikeButton().style.color = getColorFromTheme(true);
  299. getDislikeButton().style.color = getColorFromTheme(false);
  300. }
  301. }
  302. }
  303. });
  304. });
  305. }
  306. function likeClicked() {
  307. if (checkForUserAvatarButton() == true) {
  308. if (previousState == 1) {
  309. likesvalue--;
  310. createRateBar(likesvalue, dislikesvalue);
  311. setDislikes(numberFormat(dislikesvalue));
  312. previousState = 3;
  313. } else if (previousState == 2) {
  314. likesvalue++;
  315. dislikesvalue--;
  316. setDislikes(numberFormat(dislikesvalue));
  317. createRateBar(likesvalue, dislikesvalue);
  318. previousState = 1;
  319. } else if (previousState == 3) {
  320. likesvalue++;
  321. createRateBar(likesvalue, dislikesvalue);
  322. previousState = 1;
  323. }
  324. }
  325. }
  326. function dislikeClicked() {
  327. if (checkForUserAvatarButton() == true) {
  328. if (previousState == 3) {
  329. dislikesvalue++;
  330. setDislikes(numberFormat(dislikesvalue));
  331. createRateBar(likesvalue, dislikesvalue);
  332. previousState = 2;
  333. } else if (previousState == 2) {
  334. dislikesvalue--;
  335. setDislikes(numberFormat(dislikesvalue));
  336. createRateBar(likesvalue, dislikesvalue);
  337. previousState = 3;
  338. } else if (previousState == 1) {
  339. likesvalue--;
  340. dislikesvalue++;
  341. setDislikes(numberFormat(dislikesvalue));
  342. createRateBar(likesvalue, dislikesvalue);
  343. previousState = 2;
  344. }
  345. }
  346. }
  347. function setInitialState() {
  348. setState();
  349. }
  350. function getVideoId() {
  351. const urlObject = new URL(window.location.href);
  352. const pathname = urlObject.pathname;
  353. if (pathname.startsWith("/clip")) {
  354. return document.querySelector("meta[itemprop='videoId']").content;
  355. } else {
  356. if (pathname.startsWith("/shorts")) {
  357. return pathname.slice(8);
  358. }
  359. return urlObject.searchParams.get("v");
  360. }
  361. }
  362. function isVideoLoaded() {
  363. if (isMobile) {
  364. return document.getElementById("player").getAttribute("loading") == "false";
  365. }
  366. const videoId = getVideoId();
  367. return (
  368. document.querySelector(`ytd-watch-flexy[video-id='${videoId}']`) !== null
  369. );
  370. }
  371. function roundDown(num) {
  372. if (num < 1000) return num;
  373. const int = Math.floor(Math.log10(num) - 2);
  374. const decimal = int + (int % 3 ? 1 : 0);
  375. const value = Math.floor(num / 10 ** decimal);
  376. return value * 10 ** decimal;
  377. }
  378. function numberFormat(numberState) {
  379. let userLocales;
  380. try {
  381. userLocales = new URL(
  382. Array.from(document.querySelectorAll("head > link[rel='search']"))
  383. ?.find((n) => n?.getAttribute("href")?.includes("?locale="))
  384. ?.getAttribute("href")
  385. )?.searchParams?.get("locale");
  386. } catch {}
  387. let numberDisplay;
  388. if (extConfig.numberDisplayRoundDown === false) {
  389. numberDisplay = numberState;
  390. } else {
  391. numberDisplay = roundDown(numberState);
  392. }
  393. return getNumberFormatter(extConfig.numberDisplayFormat).format(
  394. numberDisplay
  395. );
  396. }
  397. function getNumberFormatter(optionSelect) {
  398. let formatterNotation;
  399. let formatterCompactDisplay;
  400. switch (optionSelect) {
  401. case "compactLong":
  402. formatterNotation = "compact";
  403. formatterCompactDisplay = "long";
  404. break;
  405. case "standard":
  406. formatterNotation = "standard";
  407. formatterCompactDisplay = "short";
  408. break;
  409. case "compactShort":
  410. default:
  411. formatterNotation = "compact";
  412. formatterCompactDisplay = "short";
  413. }
  414. const formatter = Intl.NumberFormat(
  415. document.documentElement.lang || userLocales || navigator.language,
  416. {
  417. notation: formatterNotation,
  418. compactDisplay: formatterCompactDisplay,
  419. }
  420. );
  421. return formatter;
  422. }
  423. function getColorFromTheme(voteIsLike) {
  424. let colorString;
  425. switch (extConfig.colorTheme) {
  426. case "accessible":
  427. if (voteIsLike === true) {
  428. colorString = "dodgerblue";
  429. } else {
  430. colorString = "gold";
  431. }
  432. break;
  433. case "neon":
  434. if (voteIsLike === true) {
  435. colorString = "aqua";
  436. } else {
  437. colorString = "magenta";
  438. }
  439. break;
  440. case "classic":
  441. default:
  442. if (voteIsLike === true) {
  443. colorString = "lime";
  444. } else {
  445. colorString = "red";
  446. }
  447. }
  448. return colorString;
  449. }
  450. function setEventListeners(evt) {
  451. let jsInitChecktimer;
  452. function checkForJS_Finish(check) {
  453. console.log();
  454. if (isShorts() || (getButtons()?.offsetParent && isVideoLoaded())) {
  455. const buttons = getButtons();
  456. if (!window.returnDislikeButtonlistenersSet) {
  457. cLog("Registering button listeners...");
  458. try {
  459. buttons.children[0].addEventListener("click", likeClicked);
  460. buttons.children[1].addEventListener("click", dislikeClicked);
  461. buttons.children[0].addEventListener("touchstart", likeClicked);
  462. buttons.children[1].addEventListener("touchstart", dislikeClicked);
  463. } catch {
  464. return;
  465. } //Don't spam errors into the console
  466. window.returnDislikeButtonlistenersSet = true;
  467. }
  468. setInitialState();
  469. clearInterval(jsInitChecktimer);
  470. }
  471. }
  472. cLog("Setting up...");
  473. jsInitChecktimer = setInterval(checkForJS_Finish, 111);
  474. }
  475. (function () {
  476. "use strict";
  477. window.addEventListener("yt-navigate-finish", setEventListeners, true);
  478. setEventListeners();
  479. })();
  480. if (isMobile) {
  481. let originalPush = history.pushState;
  482. history.pushState = function (...args) {
  483. window.returnDislikeButtonlistenersSet = false;
  484. setEventListeners(args[2]);
  485. return originalPush.apply(history, args);
  486. };
  487. setInterval(() => {
  488. getDislikeButton().querySelector(".button-renderer-text").innerText =
  489. mobileDislikes;
  490. }, 1000);
  491. }