Return Youtube Dislike.user.js 15 KB

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