Return Youtube Dislike.user.js 18 KB

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