Return Youtube Dislike.user.js 17 KB

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