Return Youtube Dislike.user.js 19 KB

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