Return Youtube Dislike.user.js 19 KB

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