Return Youtube Dislike.user.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. // ==UserScript==
  2. // @name Return YouTube Dislike
  3. // @namespace https://www.returnyoutubedislike.com/
  4. // @homepage https://www.returnyoutubedislike.com/
  5. // @version 3.0.1
  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. tooltipPercentageMode: "none", // [none*, dash_like, dash_dislike, both, only_like, only_dislike] Mode of showing percentage in like/dislike bar tooltip.
  36. numberDisplayReformatLikes: false, // [true, false*] Re-format like numbers (Make likes and dislikes format consistent)
  37. // END USER OPTIONS
  38. };
  39. const LIKED_STATE = "LIKED_STATE";
  40. const DISLIKED_STATE = "DISLIKED_STATE";
  41. const NEUTRAL_STATE = "NEUTRAL_STATE";
  42. let previousState = 3; //1=LIKED, 2=DISLIKED, 3=NEUTRAL
  43. let likesvalue = 0;
  44. let dislikesvalue = 0;
  45. let isMobile = location.hostname == "m.youtube.com";
  46. let isShorts = () => location.pathname.startsWith("/shorts");
  47. let mobileDislikes = 0;
  48. function cLog(text, subtext = "") {
  49. subtext = subtext.trim() === "" ? "" : `(${subtext})`;
  50. console.log(`[Return YouTube Dislikes] ${text} ${subtext}`);
  51. }
  52. function isInViewport(element) {
  53. const rect = element.getBoundingClientRect();
  54. const height = innerHeight || document.documentElement.clientHeight;
  55. const width = innerWidth || document.documentElement.clientWidth;
  56. return (
  57. rect.top >= 0 &&
  58. rect.left >= 0 &&
  59. rect.bottom <= height &&
  60. rect.right <= width
  61. );
  62. }
  63. function getButtons() {
  64. if (isShorts()) {
  65. let elements = document.querySelectorAll(
  66. isMobile
  67. ? "ytm-like-button-renderer"
  68. : "#like-button > ytd-like-button-renderer"
  69. );
  70. for (let element of elements) {
  71. if (isInViewport(element)) {
  72. return element;
  73. }
  74. }
  75. }
  76. if (isMobile) {
  77. return document.querySelector(".slim-video-action-bar-actions");
  78. }
  79. if (document.getElementById("menu-container")?.offsetParent === null) {
  80. return (
  81. document.querySelector("ytd-menu-renderer.ytd-watch-metadata > div") ??
  82. document.querySelector("ytd-menu-renderer.ytd-video-primary-info-renderer > div")
  83. )
  84. } else {
  85. return document
  86. .getElementById("menu-container")
  87. ?.querySelector("#top-level-buttons-computed");
  88. }
  89. }
  90. function getLikeButton() {
  91. return getButtons().children[0];
  92. }
  93. function getLikeTextContainer() {
  94. return (
  95. getLikeButton().querySelector("#text") ??
  96. getLikeButton().getElementsByTagName("yt-formatted-string")[0]
  97. );
  98. }
  99. function getDislikeButton() {
  100. return getButtons().children[1];
  101. }
  102. function getDislikeTextContainer() {
  103. return (
  104. getDislikeButton().querySelector("#text") ??
  105. getDislikeButton().getElementsByTagName("yt-formatted-string")[0] ??
  106. getDislikeButton().querySelector("span[role='text']")
  107. );
  108. }
  109. let mutationObserver = new Object();
  110. if (isShorts() && mutationObserver.exists !== true) {
  111. cLog("initializing mutation observer");
  112. mutationObserver.options = {
  113. childList: false,
  114. attributes: true,
  115. subtree: false,
  116. };
  117. mutationObserver.exists = true;
  118. mutationObserver.observer = new MutationObserver(function (
  119. mutationList,
  120. observer
  121. ) {
  122. mutationList.forEach((mutation) => {
  123. if (
  124. mutation.type === "attributes" &&
  125. mutation.target.nodeName === "TP-YT-PAPER-BUTTON" &&
  126. mutation.target.id === "button"
  127. ) {
  128. cLog("Short thumb button status changed");
  129. if (mutation.target.getAttribute("aria-pressed") === "true") {
  130. mutation.target.style.color =
  131. mutation.target.parentElement.parentElement.id === "like-button"
  132. ? getColorFromTheme(true)
  133. : getColorFromTheme(false);
  134. } else {
  135. mutation.target.style.color = "unset";
  136. }
  137. return;
  138. }
  139. cLog(
  140. "unexpected mutation observer event: " + mutation.target + mutation.type
  141. );
  142. });
  143. });
  144. }
  145. function isVideoLiked() {
  146. if (isMobile) {
  147. return (
  148. getLikeButton().querySelector("button").getAttribute("aria-label") ==
  149. "true"
  150. );
  151. }
  152. return getLikeButton().classList.contains("style-default-active");
  153. }
  154. function isVideoDisliked() {
  155. if (isMobile) {
  156. return (
  157. getDislikeButton().querySelector("button").getAttribute("aria-label") ==
  158. "true"
  159. );
  160. }
  161. return getDislikeButton().classList.contains("style-default-active");
  162. }
  163. function isVideoNotLiked() {
  164. if (isMobile) {
  165. return !isVideoLiked();
  166. }
  167. return getLikeButton().classList.contains("style-text");
  168. }
  169. function isVideoNotDisliked() {
  170. if (isMobile) {
  171. return !isVideoDisliked();
  172. }
  173. return getDislikeButton().classList.contains("style-text");
  174. }
  175. function checkForUserAvatarButton() {
  176. if (isMobile) {
  177. return;
  178. }
  179. if (document.querySelector("#avatar-btn")) {
  180. return true;
  181. } else {
  182. return false;
  183. }
  184. }
  185. function getState() {
  186. if (isVideoLiked()) {
  187. return LIKED_STATE;
  188. }
  189. if (isVideoDisliked()) {
  190. return DISLIKED_STATE;
  191. }
  192. return NEUTRAL_STATE;
  193. }
  194. function setLikes(likesCount) {
  195. if (isMobile) {
  196. getButtons().children[0].querySelector(".button-renderer-text").innerText =
  197. likesCount;
  198. return;
  199. }
  200. getLikeTextContainer().innerText = likesCount;
  201. }
  202. function setDislikes(dislikesCount) {
  203. if (isMobile) {
  204. mobileDislikes = dislikesCount;
  205. return;
  206. }
  207. getDislikeTextContainer().innerText = dislikesCount;
  208. }
  209. function getLikeCountFromButton() {
  210. if (isShorts()) {
  211. //Youtube Shorts don't work with this query. It's not nessecary; we can skip it and still see the results.
  212. //It should be possible to fix this function, but it's not critical to showing the dislike count.
  213. return false;
  214. }
  215. let likesStr = getLikeButton()
  216. .querySelector("yt-formatted-string#text")
  217. .getAttribute("aria-label")
  218. .replace(/\D/g, "");
  219. return likesStr.length > 0 ? parseInt(likesStr) : false;
  220. }
  221. (typeof GM_addStyle != "undefined"
  222. ? GM_addStyle
  223. : (styles) => {
  224. let styleNode = document.createElement("style");
  225. styleNode.type = "text/css";
  226. styleNode.innerText = styles;
  227. document.head.appendChild(styleNode);
  228. })(`
  229. #return-youtube-dislike-bar-container {
  230. background: var(--yt-spec-icon-disabled);
  231. border-radius: 2px;
  232. }
  233. #return-youtube-dislike-bar {
  234. background: var(--yt-spec-text-primary);
  235. border-radius: 2px;
  236. transition: all 0.15s ease-in-out;
  237. }
  238. .ryd-tooltip {
  239. position: relative;
  240. display: block;
  241. height: 2px;
  242. top: 9px;
  243. }
  244. .ryd-tooltip-bar-container {
  245. width: 100%;
  246. height: 2px;
  247. position: absolute;
  248. padding-top: 6px;
  249. padding-bottom: 28px;
  250. top: -6px;
  251. }
  252. `);
  253. function createRateBar(likes, dislikes) {
  254. if (isMobile) {
  255. return;
  256. }
  257. let rateBar = document.getElementById("return-youtube-dislike-bar-container");
  258. const widthPx =
  259. getButtons().children[0].clientWidth +
  260. getButtons().children[1].clientWidth +
  261. 8;
  262. const widthPercent =
  263. likes + dislikes > 0 ? (likes / (likes + dislikes)) * 100 : 50;
  264. var likePercentage = parseFloat(widthPercent.toFixed(1));
  265. const dislikePercentage = (100 - likePercentage).toLocaleString();
  266. likePercentage = likePercentage.toLocaleString();
  267. var tooltipInnerHTML;
  268. switch (extConfig.tooltipPercentageMode) {
  269. case "dash_like":
  270. tooltipInnerHTML = `${likes.toLocaleString()}&nbsp;/&nbsp;${dislikes.toLocaleString()}&nbsp;&nbsp;-&nbsp;&nbsp;${likePercentage}%`;
  271. break;
  272. case "dash_dislike":
  273. tooltipInnerHTML = `${likes.toLocaleString()}&nbsp;/&nbsp;${dislikes.toLocaleString()}&nbsp;&nbsp;-&nbsp;&nbsp;${dislikePercentage}%`;
  274. break;
  275. case "both":
  276. tooltipInnerHTML = `${likePercentage}%&nbsp;/&nbsp;${dislikePercentage}%`;
  277. break;
  278. case "only_like":
  279. tooltipInnerHTML = `${likePercentage}%`;
  280. break;
  281. case "only_dislike":
  282. tooltipInnerHTML = `${dislikePercentage}%`;
  283. break;
  284. default:
  285. tooltipInnerHTML = `${likes.toLocaleString()}&nbsp;/&nbsp;${dislikes.toLocaleString()}`;
  286. }
  287. if (!rateBar && !isMobile) {
  288. let colorLikeStyle = "";
  289. let colorDislikeStyle = "";
  290. if (extConfig.coloredBar) {
  291. colorLikeStyle = "; background-color: " + getColorFromTheme(true);
  292. colorDislikeStyle = "; background-color: " + getColorFromTheme(false);
  293. }
  294. document.getElementById("menu-container").insertAdjacentHTML(
  295. "beforeend",
  296. `
  297. <div class="ryd-tooltip" style="width: ${widthPx}px">
  298. <div class="ryd-tooltip-bar-container">
  299. <div
  300. id="return-youtube-dislike-bar-container"
  301. style="width: 100%; height: 2px;${colorDislikeStyle}"
  302. >
  303. <div
  304. id="return-youtube-dislike-bar"
  305. style="width: ${widthPercent}%; height: 100%${colorDislikeStyle}"
  306. ></div>
  307. </div>
  308. </div>
  309. <tp-yt-paper-tooltip position="top" id="ryd-dislike-tooltip" class="style-scope ytd-sentiment-bar-renderer" role="tooltip" tabindex="-1">
  310. <!--css-build:shady-->${tooltipInnerHTML}
  311. </tp-yt-paper-tooltip>
  312. </div>
  313. `
  314. );
  315. } else {
  316. document.getElementById(
  317. "return-youtube-dislike-bar-container"
  318. ).style.width = widthPx + "px";
  319. document.getElementById("return-youtube-dislike-bar").style.width =
  320. widthPercent + "%";
  321. document.querySelector("#ryd-dislike-tooltip > #tooltip").innerHTML =
  322. tooltipInnerHTML;
  323. if (extConfig.coloredBar) {
  324. document.getElementById(
  325. "return-youtube-dislike-bar-container"
  326. ).style.backgroundColor = getColorFromTheme(false);
  327. document.getElementById(
  328. "return-youtube-dislike-bar"
  329. ).style.backgroundColor = getColorFromTheme(true);
  330. }
  331. }
  332. }
  333. function setState() {
  334. cLog("Fetching votes...");
  335. let statsSet = false;
  336. fetch(
  337. `https://returnyoutubedislikeapi.com/votes?videoId=${getVideoId()}`
  338. ).then((response) => {
  339. response.json().then((json) => {
  340. if (json && !("traceId" in response) && !statsSet) {
  341. const { dislikes, likes } = json;
  342. cLog(`Received count: ${dislikes}`);
  343. likesvalue = likes;
  344. dislikesvalue = dislikes;
  345. setDislikes(numberFormat(dislikes));
  346. if (extConfig.numberDisplayReformatLikes === true) {
  347. const nativeLikes = getLikeCountFromButton();
  348. if (nativeLikes !== false) {
  349. setLikes(numberFormat(nativeLikes));
  350. }
  351. }
  352. createRateBar(likes, dislikes);
  353. if (extConfig.coloredThumbs === true) {
  354. if (isShorts()) {
  355. // for shorts, leave deactived buttons in default color
  356. let shortLikeButton = getLikeButton().querySelector(
  357. "tp-yt-paper-button#button"
  358. );
  359. let shortDislikeButton = getDislikeButton().querySelector(
  360. "tp-yt-paper-button#button"
  361. );
  362. if (shortLikeButton.getAttribute("aria-pressed") === "true") {
  363. shortLikeButton.style.color = getColorFromTheme(true);
  364. }
  365. if (shortDislikeButton.getAttribute("aria-pressed") === "true") {
  366. shortDislikeButton.style.color = getColorFromTheme(false);
  367. }
  368. mutationObserver.observer.observe(
  369. shortLikeButton,
  370. mutationObserver.options
  371. );
  372. mutationObserver.observer.observe(
  373. shortDislikeButton,
  374. mutationObserver.options
  375. );
  376. } else {
  377. getLikeButton().style.color = getColorFromTheme(true);
  378. getDislikeButton().style.color = getColorFromTheme(false);
  379. }
  380. }
  381. }
  382. });
  383. });
  384. }
  385. function likeClicked() {
  386. if (checkForUserAvatarButton() == true) {
  387. if (previousState == 1) {
  388. likesvalue--;
  389. createRateBar(likesvalue, dislikesvalue);
  390. setDislikes(numberFormat(dislikesvalue));
  391. previousState = 3;
  392. } else if (previousState == 2) {
  393. likesvalue++;
  394. dislikesvalue--;
  395. setDislikes(numberFormat(dislikesvalue));
  396. createRateBar(likesvalue, dislikesvalue);
  397. previousState = 1;
  398. } else if (previousState == 3) {
  399. likesvalue++;
  400. createRateBar(likesvalue, dislikesvalue);
  401. previousState = 1;
  402. }
  403. if (extConfig.numberDisplayReformatLikes === true) {
  404. const nativeLikes = getLikeCountFromButton();
  405. if (nativeLikes !== false) {
  406. setLikes(numberFormat(nativeLikes));
  407. }
  408. }
  409. }
  410. }
  411. function dislikeClicked() {
  412. if (checkForUserAvatarButton() == true) {
  413. if (previousState == 3) {
  414. dislikesvalue++;
  415. setDislikes(numberFormat(dislikesvalue));
  416. createRateBar(likesvalue, dislikesvalue);
  417. previousState = 2;
  418. } else if (previousState == 2) {
  419. dislikesvalue--;
  420. setDislikes(numberFormat(dislikesvalue));
  421. createRateBar(likesvalue, dislikesvalue);
  422. previousState = 3;
  423. } else if (previousState == 1) {
  424. likesvalue--;
  425. dislikesvalue++;
  426. setDislikes(numberFormat(dislikesvalue));
  427. createRateBar(likesvalue, dislikesvalue);
  428. previousState = 2;
  429. if (extConfig.numberDisplayReformatLikes === true) {
  430. const nativeLikes = getLikeCountFromButton();
  431. if (nativeLikes !== false) {
  432. setLikes(numberFormat(nativeLikes));
  433. }
  434. }
  435. }
  436. }
  437. }
  438. function setInitialState() {
  439. setState();
  440. }
  441. function getVideoId() {
  442. const urlObject = new URL(window.location.href);
  443. const pathname = urlObject.pathname;
  444. if (pathname.startsWith("/clip")) {
  445. return document.querySelector("meta[itemprop='videoId']").content;
  446. } else {
  447. if (pathname.startsWith("/shorts")) {
  448. return pathname.slice(8);
  449. }
  450. return urlObject.searchParams.get("v");
  451. }
  452. }
  453. function isVideoLoaded() {
  454. if (isMobile) {
  455. return document.getElementById("player").getAttribute("loading") == "false";
  456. }
  457. const videoId = getVideoId();
  458. return (
  459. document.querySelector(`ytd-watch-flexy[video-id='${videoId}']`) !== null
  460. );
  461. }
  462. function roundDown(num) {
  463. if (num < 1000) return num;
  464. const int = Math.floor(Math.log10(num) - 2);
  465. const decimal = int + (int % 3 ? 1 : 0);
  466. const value = Math.floor(num / 10 ** decimal);
  467. return value * 10 ** decimal;
  468. }
  469. function numberFormat(numberState) {
  470. let numberDisplay;
  471. if (extConfig.numberDisplayRoundDown === false) {
  472. numberDisplay = numberState;
  473. } else {
  474. numberDisplay = roundDown(numberState);
  475. }
  476. return getNumberFormatter(extConfig.numberDisplayFormat).format(
  477. numberDisplay
  478. );
  479. }
  480. function getNumberFormatter(optionSelect) {
  481. let userLocales;
  482. if (document.documentElement.lang) {
  483. userLocales = document.documentElement.lang;
  484. } else if (navigator.language) {
  485. userLocales = navigator.language;
  486. } else {
  487. try {
  488. userLocales = new URL(
  489. Array.from(document.querySelectorAll("head > link[rel='search']"))
  490. ?.find((n) => n?.getAttribute("href")?.includes("?locale="))
  491. ?.getAttribute("href")
  492. )?.searchParams?.get("locale");
  493. } catch {
  494. cLog(
  495. "Cannot find browser locale. Use en as default for number formatting."
  496. );
  497. userLocales = "en";
  498. }
  499. }
  500. let formatterNotation;
  501. let formatterCompactDisplay;
  502. switch (optionSelect) {
  503. case "compactLong":
  504. formatterNotation = "compact";
  505. formatterCompactDisplay = "long";
  506. break;
  507. case "standard":
  508. formatterNotation = "standard";
  509. formatterCompactDisplay = "short";
  510. break;
  511. case "compactShort":
  512. default:
  513. formatterNotation = "compact";
  514. formatterCompactDisplay = "short";
  515. }
  516. const formatter = Intl.NumberFormat(userLocales, {
  517. notation: formatterNotation,
  518. compactDisplay: formatterCompactDisplay,
  519. });
  520. return formatter;
  521. }
  522. function getColorFromTheme(voteIsLike) {
  523. let colorString;
  524. switch (extConfig.colorTheme) {
  525. case "accessible":
  526. if (voteIsLike === true) {
  527. colorString = "dodgerblue";
  528. } else {
  529. colorString = "gold";
  530. }
  531. break;
  532. case "neon":
  533. if (voteIsLike === true) {
  534. colorString = "aqua";
  535. } else {
  536. colorString = "magenta";
  537. }
  538. break;
  539. case "classic":
  540. default:
  541. if (voteIsLike === true) {
  542. colorString = "lime";
  543. } else {
  544. colorString = "red";
  545. }
  546. }
  547. return colorString;
  548. }
  549. function setEventListeners(evt) {
  550. let jsInitChecktimer;
  551. function checkForJS_Finish() {
  552. //console.log();
  553. if (isShorts() || (getButtons()?.offsetParent && isVideoLoaded())) {
  554. const buttons = getButtons();
  555. if (!window.returnDislikeButtonlistenersSet) {
  556. cLog("Registering button listeners...");
  557. try {
  558. buttons.children[0].addEventListener("click", likeClicked);
  559. buttons.children[1].addEventListener("click", dislikeClicked);
  560. buttons.children[0].addEventListener("touchstart", likeClicked);
  561. buttons.children[1].addEventListener("touchstart", dislikeClicked);
  562. } catch {
  563. return;
  564. } //Don't spam errors into the console
  565. window.returnDislikeButtonlistenersSet = true;
  566. }
  567. setInitialState();
  568. clearInterval(jsInitChecktimer);
  569. }
  570. }
  571. cLog("Setting up...");
  572. jsInitChecktimer = setInterval(checkForJS_Finish, 111);
  573. }
  574. (function () {
  575. "use strict";
  576. window.addEventListener("yt-navigate-finish", setEventListeners, true);
  577. setEventListeners();
  578. })();
  579. if (isMobile) {
  580. let originalPush = history.pushState;
  581. history.pushState = function (...args) {
  582. window.returnDislikeButtonlistenersSet = false;
  583. setEventListeners(args[2]);
  584. return originalPush.apply(history, args);
  585. };
  586. setInterval(() => {
  587. getDislikeButton().querySelector(".button-renderer-text").innerText =
  588. mobileDislikes;
  589. }, 1000);
  590. }