Return Youtube Dislike.user.js 13 KB

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