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