Return Youtube Dislike.user.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. let colorLikeStyle = "";
  200. let colorDislikeStyle = "";
  201. if (extConfig.coloredBar) {
  202. colorLikeStyle = "; background-color: " + getColorFromTheme(true);
  203. colorDislikeStyle = "; background-color: " + getColorFromTheme(false);
  204. }
  205. document.getElementById("menu-container").insertAdjacentHTML(
  206. "beforeend",
  207. `
  208. <div class="ryd-tooltip" style="width: ${widthPx}px">
  209. <div class="ryd-tooltip-bar-container">
  210. <div
  211. id="return-youtube-dislike-bar-container"
  212. style="width: 100%; height: 2px;${colorDislikeStyle}"
  213. >
  214. <div
  215. id="return-youtube-dislike-bar"
  216. style="width: ${widthPercent}%; height: 100%${colorDislikeStyle}"
  217. ></div>
  218. </div>
  219. </div>
  220. <tp-yt-paper-tooltip position="top" id="ryd-dislike-tooltip" class="style-scope ytd-sentiment-bar-renderer" role="tooltip" tabindex="-1">
  221. <!--css-build:shady-->${likes.toLocaleString()}&nbsp;/&nbsp;${dislikes.toLocaleString()}
  222. </tp-yt-paper-tooltip>
  223. </div>
  224. `
  225. );
  226. } else {
  227. document.getElementById(
  228. "return-youtube-dislike-bar-container"
  229. ).style.width = widthPx + "px";
  230. document.getElementById("return-youtube-dislike-bar").style.width =
  231. widthPercent + "%";
  232. document.querySelector(
  233. "#ryd-dislike-tooltip > #tooltip"
  234. ).innerHTML = `${likes.toLocaleString()}&nbsp;/&nbsp;${dislikes.toLocaleString()}`;
  235. if (extConfig.coloredBar) {
  236. document.getElementById("return-youtube-dislike-bar-container").style.backgroundColor =
  237. getColorFromTheme(false);
  238. document.getElementById("return-youtube-dislike-bar").style.backgroundColor =
  239. getColorFromTheme(true);
  240. }
  241. }
  242. }
  243. function setState() {
  244. cLog("Fetching votes...");
  245. let statsSet = false;
  246. fetch(
  247. `https://returnyoutubedislikeapi.com/votes?videoId=${getVideoId()}`
  248. ).then((response) => {
  249. response.json().then((json) => {
  250. if (json && !("traceId" in response) && !statsSet) {
  251. const { dislikes, likes } = json;
  252. cLog(`Received count: ${dislikes}`);
  253. likesvalue = likes;
  254. dislikesvalue = dislikes;
  255. setDislikes(numberFormat(dislikes));
  256. createRateBar(likes, dislikes);
  257. if (extConfig.coloredThumbs === true) {
  258. getLikeButton().style.color = getColorFromTheme(true);
  259. getDislikeButton().style.color = getColorFromTheme(false);
  260. }
  261. }
  262. });
  263. });
  264. }
  265. function likeClicked() {
  266. if (checkForUserAvatarButton() == true) {
  267. if (previousState == 1) {
  268. likesvalue--;
  269. createRateBar(likesvalue, dislikesvalue);
  270. setDislikes(numberFormat(dislikesvalue));
  271. previousState = 3;
  272. } else if (previousState == 2) {
  273. likesvalue++;
  274. dislikesvalue--;
  275. setDislikes(numberFormat(dislikesvalue));
  276. createRateBar(likesvalue, dislikesvalue);
  277. previousState = 1;
  278. } else if (previousState == 3) {
  279. likesvalue++;
  280. createRateBar(likesvalue, dislikesvalue);
  281. previousState = 1;
  282. }
  283. }
  284. }
  285. function dislikeClicked() {
  286. if (checkForUserAvatarButton() == true) {
  287. if (previousState == 3) {
  288. dislikesvalue++;
  289. setDislikes(numberFormat(dislikesvalue));
  290. createRateBar(likesvalue, dislikesvalue);
  291. previousState = 2;
  292. } else if (previousState == 2) {
  293. dislikesvalue--;
  294. setDislikes(numberFormat(dislikesvalue));
  295. createRateBar(likesvalue, dislikesvalue);
  296. previousState = 3;
  297. } else if (previousState == 1) {
  298. likesvalue--;
  299. dislikesvalue++;
  300. setDislikes(numberFormat(dislikesvalue));
  301. createRateBar(likesvalue, dislikesvalue);
  302. previousState = 2;
  303. }
  304. }
  305. }
  306. function setInitialState() {
  307. setState();
  308. }
  309. function getVideoId() {
  310. const urlObject = new URL(window.location.href);
  311. const pathname = urlObject.pathname;
  312. if (pathname.startsWith("/clip")) {
  313. return document.querySelector("meta[itemprop='videoId']").content;
  314. } else {
  315. if (pathname.startsWith("/shorts")) {
  316. return pathname.slice(8);
  317. }
  318. return urlObject.searchParams.get("v");
  319. }
  320. }
  321. function isVideoLoaded() {
  322. if (isMobile) {
  323. return document.getElementById("player").getAttribute("loading") == "false";
  324. }
  325. const videoId = getVideoId();
  326. return (
  327. document.querySelector(`ytd-watch-flexy[video-id='${videoId}']`) !== null
  328. );
  329. }
  330. function roundDown(num) {
  331. if (num < 1000) return num;
  332. const int = Math.floor(Math.log10(num) - 2);
  333. const decimal = int + (int % 3 ? 1 : 0);
  334. const value = Math.floor(num / 10 ** decimal);
  335. return value * 10 ** decimal;
  336. }
  337. function numberFormat(numberState) {
  338. let userLocales;
  339. try {
  340. userLocales = new URL(
  341. Array.from(document.querySelectorAll("head > link[rel='search']"))
  342. ?.find((n) => n?.getAttribute("href")?.includes("?locale="))
  343. ?.getAttribute("href")
  344. )?.searchParams?.get("locale");
  345. } catch {}
  346. let numberDisplay;
  347. if (extConfig.numberDisplayRoundDown === false) {
  348. numberDisplay = numberState;
  349. } else {
  350. numberDisplay = roundDown(numberState);
  351. }
  352. return getNumberFormatter(extConfig.numberDisplayFormat).format(
  353. numberDisplay
  354. );
  355. }
  356. function getNumberFormatter(optionSelect) {
  357. let formatterNotation;
  358. let formatterCompactDisplay;
  359. switch (optionSelect) {
  360. case "compactLong":
  361. formatterNotation = "compact";
  362. formatterCompactDisplay = "long";
  363. break;
  364. case "standard":
  365. formatterNotation = "standard";
  366. formatterCompactDisplay = "short";
  367. break;
  368. case "compactShort":
  369. default:
  370. formatterNotation = "compact";
  371. formatterCompactDisplay = "short";
  372. }
  373. const formatter = Intl.NumberFormat(
  374. document.documentElement.lang || userLocales || navigator.language,
  375. {
  376. notation: formatterNotation,
  377. compactDisplay: formatterCompactDisplay,
  378. }
  379. );
  380. return formatter;
  381. }
  382. function getColorFromTheme(voteIsLike) {
  383. let colorString;
  384. switch (extConfig.colorTheme) {
  385. case "accessible":
  386. if (voteIsLike === true) {
  387. colorString = "dodgerblue";
  388. } else {
  389. colorString = "gold";
  390. }
  391. break;
  392. case "neon":
  393. if (voteIsLike === true) {
  394. colorString = "aqua";
  395. } else {
  396. colorString = "magenta";
  397. }
  398. break;
  399. case "classic":
  400. default:
  401. if (voteIsLike === true) {
  402. colorString = "lime";
  403. } else {
  404. colorString = "red";
  405. }
  406. }
  407. return colorString;
  408. }
  409. function setEventListeners(evt) {
  410. let jsInitChecktimer;
  411. function checkForJS_Finish(check) {
  412. console.log();
  413. if (isShorts() || (getButtons()?.offsetParent && isVideoLoaded())) {
  414. const buttons = getButtons();
  415. if (!window.returnDislikeButtonlistenersSet) {
  416. cLog("Registering button listeners...");
  417. try {
  418. buttons.children[0].addEventListener("click", likeClicked);
  419. buttons.children[1].addEventListener("click", dislikeClicked);
  420. buttons.children[0].addEventListener("touchstart", likeClicked);
  421. buttons.children[1].addEventListener("touchstart", dislikeClicked);
  422. } catch {
  423. return;
  424. } //Don't spam errors into the console
  425. window.returnDislikeButtonlistenersSet = true;
  426. }
  427. setInitialState();
  428. clearInterval(jsInitChecktimer);
  429. }
  430. }
  431. cLog("Setting up...");
  432. jsInitChecktimer = setInterval(checkForJS_Finish, 111);
  433. }
  434. (function () {
  435. "use strict";
  436. window.addEventListener("yt-navigate-finish", setEventListeners, true);
  437. setEventListeners();
  438. })();
  439. if (isMobile) {
  440. let originalPush = history.pushState;
  441. history.pushState = function (...args) {
  442. window.returnDislikeButtonlistenersSet = false;
  443. setEventListeners(args[2]);
  444. return originalPush.apply(history, args);
  445. };
  446. setInterval(() => {
  447. getDislikeButton().querySelector(".button-renderer-text").innerText =
  448. mobileDislikes;
  449. }, 1000);
  450. }