Return Youtube Dislike.user.js 15 KB

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