Return YouTube Dislike

Return of the YouTube Dislike, Based off https://www.returnyoutubedislike.com/

目前為 2022-11-10 提交的版本,檢視 最新版本

  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. // @grant GM.xmlHttpRequest
  19. // @connect youtube.com
  20. // @grant GM_addStyle
  21. // @run-at document-end
  22. // ==/UserScript==
  23.  
  24. const extConfig = {
  25. // BEGIN USER OPTIONS
  26. // You may change the following variables to allowed values listed in the corresponding brackets (* means default). Keep the style and keywords intact.
  27. showUpdatePopup: false, // [true, false*] Show a popup tab after extension update (See what's new)
  28. disableVoteSubmission: false, // [true, false*] Disable like/dislike submission (Stops counting your likes and dislikes)
  29. coloredThumbs: false, // [true, false*] Colorize thumbs (Use custom colors for thumb icons)
  30. coloredBar: false, // [true, false*] Colorize ratio bar (Use custom colors for ratio bar)
  31. colorTheme: "classic", // [classic*, accessible, neon] Color theme (red/green, blue/yellow, pink/cyan)
  32. 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)
  33. numberDisplayRoundDown: true, // [true*, false] Round down numbers (Show rounded down numbers)
  34. tooltipPercentageMode: "none", // [none*, dash_like, dash_dislike, both, only_like, only_dislike] Mode of showing percentage in like/dislike bar tooltip.
  35. numberDisplayReformatLikes: false, // [true, false*] Re-format like numbers (Make likes and dislikes format consistent)
  36. // END USER OPTIONS
  37. };
  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.  
  46. let isMobile = location.hostname == "m.youtube.com";
  47. let isShorts = () => location.pathname.startsWith("/shorts");
  48. let mobileDislikes = 0;
  49. function cLog(text, subtext = "") {
  50. subtext = subtext.trim() === "" ? "" : `(${subtext})`;
  51. console.log(`[Return YouTube Dislikes] ${text} ${subtext}`);
  52. }
  53.  
  54. function isInViewport(element) {
  55. const rect = element.getBoundingClientRect();
  56. const height = innerHeight || document.documentElement.clientHeight;
  57. const width = innerWidth || document.documentElement.clientWidth;
  58. return (
  59. // When short (channel) is ignored, the element (like/dislike AND short itself) is
  60. // hidden with a 0 DOMRect. In this case, consider it outside of Viewport
  61. !(rect.top == 0 && rect.left == 0 && rect.bottom == 0 && rect.right == 0) &&
  62. rect.top >= 0 &&
  63. rect.left >= 0 &&
  64. rect.bottom <= height &&
  65. rect.right <= width
  66. );
  67. }
  68.  
  69. function getButtons() {
  70. if (isShorts()) {
  71. let elements = document.querySelectorAll(
  72. isMobile
  73. ? "ytm-like-button-renderer"
  74. : "#like-button > ytd-like-button-renderer"
  75. );
  76. for (let element of elements) {
  77. if (isInViewport(element)) {
  78. return element;
  79. }
  80. }
  81. }
  82. if (isMobile) {
  83. return document.querySelector(".slim-video-action-bar-actions");
  84. }
  85. if (document.getElementById("menu-container")?.offsetParent === null) {
  86. return document.querySelector("ytd-menu-renderer.ytd-watch-metadata > div");
  87. } else {
  88. return document
  89. .getElementById("menu-container")
  90. ?.querySelector("#top-level-buttons-computed");
  91. }
  92. }
  93.  
  94. function getLikeButton() {
  95. return getButtons().children[0];
  96. }
  97.  
  98. function getLikeTextContainer() {
  99. return (
  100. getLikeButton().querySelector("#text") ??
  101. getLikeButton().getElementsByTagName("yt-formatted-string")[0] ??
  102. getLikeButton().querySelector("span[role='text']")
  103. );
  104. }
  105.  
  106. function getDislikeButton() {
  107. return getButtons().children[1];
  108. }
  109.  
  110. function getDislikeTextContainer() {
  111. return (
  112. getDislikeButton().querySelector("#text") ??
  113. getDislikeButton().getElementsByTagName("yt-formatted-string")[0]
  114. );
  115. }
  116.  
  117. let mutationObserver = new Object();
  118.  
  119. if (isShorts() && mutationObserver.exists !== true) {
  120. cLog("initializing mutation observer");
  121. mutationObserver.options = {
  122. childList: false,
  123. attributes: true,
  124. subtree: false,
  125. };
  126. mutationObserver.exists = true;
  127. mutationObserver.observer = new MutationObserver(function (
  128. mutationList,
  129. observer
  130. ) {
  131. mutationList.forEach((mutation) => {
  132. if (
  133. mutation.type === "attributes" &&
  134. mutation.target.nodeName === "TP-YT-PAPER-BUTTON" &&
  135. mutation.target.id === "button"
  136. ) {
  137. cLog("Short thumb button status changed");
  138. if (mutation.target.getAttribute("aria-pressed") === "true") {
  139. mutation.target.style.color =
  140. mutation.target.parentElement.parentElement.id === "like-button"
  141. ? getColorFromTheme(true)
  142. : getColorFromTheme(false);
  143. } else {
  144. mutation.target.style.color = "unset";
  145. }
  146. return;
  147. }
  148. cLog(
  149. "unexpected mutation observer event: " + mutation.target + mutation.type
  150. );
  151. });
  152. });
  153. }
  154.  
  155. function isVideoLiked() {
  156. if (isMobile) {
  157. return (
  158. getLikeButton().querySelector("button").getAttribute("aria-label") ==
  159. "true"
  160. );
  161. }
  162. return getLikeButton().classList.contains("style-default-active");
  163. }
  164.  
  165. function isVideoDisliked() {
  166. if (isMobile) {
  167. return (
  168. getDislikeButton().querySelector("button").getAttribute("aria-label") ==
  169. "true"
  170. );
  171. }
  172. return getDislikeButton().classList.contains("style-default-active");
  173. }
  174.  
  175. function isVideoNotLiked() {
  176. if (isMobile) {
  177. return !isVideoLiked();
  178. }
  179. return getLikeButton().classList.contains("style-text");
  180. }
  181.  
  182. function isVideoNotDisliked() {
  183. if (isMobile) {
  184. return !isVideoDisliked();
  185. }
  186. return getDislikeButton().classList.contains("style-text");
  187. }
  188.  
  189. function checkForUserAvatarButton() {
  190. if (isMobile) {
  191. return;
  192. }
  193. if (document.querySelector("#avatar-btn")) {
  194. return true;
  195. } else {
  196. return false;
  197. }
  198. }
  199.  
  200. function getState() {
  201. if (isVideoLiked()) {
  202. return LIKED_STATE;
  203. }
  204. if (isVideoDisliked()) {
  205. return DISLIKED_STATE;
  206. }
  207. return NEUTRAL_STATE;
  208. }
  209.  
  210. function setLikes(likesCount) {
  211. if (isMobile) {
  212. getButtons().children[0].querySelector(".button-renderer-text").innerText =
  213. likesCount;
  214. return;
  215. }
  216. getLikeTextContainer().innerText = likesCount;
  217. }
  218.  
  219. function setDislikes(dislikesCount) {
  220. if (isMobile) {
  221. mobileDislikes = dislikesCount;
  222. return;
  223. }
  224. getDislikeTextContainer()?.removeAttribute('is-empty');
  225. getDislikeTextContainer().innerText = dislikesCount;
  226. }
  227.  
  228. function getLikeCountFromButton() {
  229. try {
  230. if (isShorts()) {
  231. //Youtube Shorts don't work with this query. It's not necessary; we can skip it and still see the results.
  232. //It should be possible to fix this function, but it's not critical to showing the dislike count.
  233. return false;
  234. }
  235. let likeButton = getLikeButton()
  236. .querySelector("yt-formatted-string#text") ??
  237. getLikeButton().querySelector("button");
  238.  
  239. let likesStr = likeButton.getAttribute("aria-label")
  240. .replace(/\D/g, "");
  241. return likesStr.length > 0 ? parseInt(likesStr) : false;
  242. }
  243. catch {
  244. return false;
  245. }
  246.  
  247. }
  248.  
  249. (typeof GM_addStyle != "undefined"
  250. ? GM_addStyle
  251. : (styles) => {
  252. let styleNode = document.createElement("style");
  253. styleNode.type = "text/css";
  254. styleNode.innerText = styles;
  255. document.head.appendChild(styleNode);
  256. })(`
  257. #return-youtube-dislike-bar-container {
  258. background: var(--yt-spec-icon-disabled);
  259. border-radius: 2px;
  260. }
  261.  
  262. #return-youtube-dislike-bar {
  263. background: var(--yt-spec-text-primary);
  264. border-radius: 2px;
  265. transition: all 0.15s ease-in-out;
  266. }
  267.  
  268. .ryd-tooltip {
  269. position: relative;
  270. display: block;
  271. height: 2px;
  272. top: 9px;
  273. }
  274.  
  275. .ryd-tooltip-bar-container {
  276. width: 100%;
  277. height: 2px;
  278. position: absolute;
  279. padding-top: 6px;
  280. padding-bottom: 28px;
  281. top: -6px;
  282. }
  283. `);
  284.  
  285. function createRateBar(likes, dislikes) {
  286. if (isMobile) {
  287. return;
  288. }
  289. let rateBar = document.getElementById("return-youtube-dislike-bar-container");
  290.  
  291. const widthPx =
  292. getButtons().children[0].clientWidth +
  293. getButtons().children[1].clientWidth +
  294. 8;
  295.  
  296. const widthPercent =
  297. likes + dislikes > 0 ? (likes / (likes + dislikes)) * 100 : 50;
  298.  
  299. var likePercentage = parseFloat(widthPercent.toFixed(1));
  300. const dislikePercentage = (100 - likePercentage).toLocaleString();
  301. likePercentage = likePercentage.toLocaleString();
  302.  
  303. var tooltipInnerHTML;
  304. switch (extConfig.tooltipPercentageMode) {
  305. case "dash_like":
  306. tooltipInnerHTML = `${likes.toLocaleString()}&nbsp;/&nbsp;${dislikes.toLocaleString()}&nbsp;&nbsp;-&nbsp;&nbsp;${likePercentage}%`;
  307. break;
  308. case "dash_dislike":
  309. tooltipInnerHTML = `${likes.toLocaleString()}&nbsp;/&nbsp;${dislikes.toLocaleString()}&nbsp;&nbsp;-&nbsp;&nbsp;${dislikePercentage}%`;
  310. break;
  311. case "both":
  312. tooltipInnerHTML = `${likePercentage}%&nbsp;/&nbsp;${dislikePercentage}%`;
  313. break;
  314. case "only_like":
  315. tooltipInnerHTML = `${likePercentage}%`;
  316. break;
  317. case "only_dislike":
  318. tooltipInnerHTML = `${dislikePercentage}%`;
  319. break;
  320. default:
  321. tooltipInnerHTML = `${likes.toLocaleString()}&nbsp;/&nbsp;${dislikes.toLocaleString()}`;
  322. }
  323.  
  324. if (!rateBar && !isMobile) {
  325. let colorLikeStyle = "";
  326. let colorDislikeStyle = "";
  327. if (extConfig.coloredBar) {
  328. colorLikeStyle = "; background-color: " + getColorFromTheme(true);
  329. colorDislikeStyle = "; background-color: " + getColorFromTheme(false);
  330. }
  331.  
  332. document.getElementById("menu-container").insertAdjacentHTML(
  333. "beforeend",
  334. `
  335. <div class="ryd-tooltip" style="width: ${widthPx}px">
  336. <div class="ryd-tooltip-bar-container">
  337. <div
  338. id="return-youtube-dislike-bar-container"
  339. style="width: 100%; height: 2px;${colorDislikeStyle}"
  340. >
  341. <div
  342. id="return-youtube-dislike-bar"
  343. style="width: ${widthPercent}%; height: 100%${colorDislikeStyle}"
  344. ></div>
  345. </div>
  346. </div>
  347. <tp-yt-paper-tooltip position="top" id="ryd-dislike-tooltip" class="style-scope ytd-sentiment-bar-renderer" role="tooltip" tabindex="-1">
  348. <!--css-build:shady-->${tooltipInnerHTML}
  349. </tp-yt-paper-tooltip>
  350. </div>
  351. `
  352. );
  353. } else {
  354. document.getElementById(
  355. "return-youtube-dislike-bar-container"
  356. ).style.width = widthPx + "px";
  357. document.getElementById("return-youtube-dislike-bar").style.width =
  358. widthPercent + "%";
  359.  
  360. document.querySelector("#ryd-dislike-tooltip > #tooltip").innerHTML =
  361. tooltipInnerHTML;
  362.  
  363. if (extConfig.coloredBar) {
  364. document.getElementById(
  365. "return-youtube-dislike-bar-container"
  366. ).style.backgroundColor = getColorFromTheme(false);
  367. document.getElementById(
  368. "return-youtube-dislike-bar"
  369. ).style.backgroundColor = getColorFromTheme(true);
  370. }
  371. }
  372. }
  373.  
  374. function setState() {
  375. cLog("Fetching votes...");
  376. let statsSet = false;
  377.  
  378. fetch(
  379. `https://returnyoutubedislikeapi.com/votes?videoId=${getVideoId()}`
  380. ).then((response) => {
  381. response.json().then((json) => {
  382. if (json && !("traceId" in response) && !statsSet) {
  383. const { dislikes, likes } = json;
  384. cLog(`Received count: ${dislikes}`);
  385. likesvalue = likes;
  386. dislikesvalue = dislikes;
  387. setDislikes(numberFormat(dislikes));
  388. if (extConfig.numberDisplayReformatLikes === true) {
  389. const nativeLikes = getLikeCountFromButton();
  390. if (nativeLikes !== false) {
  391. setLikes(numberFormat(nativeLikes));
  392. }
  393. }
  394. createRateBar(likes, dislikes);
  395. if (extConfig.coloredThumbs === true) {
  396. if (isShorts()) {
  397. // for shorts, leave deactived buttons in default color
  398. let shortLikeButton = getLikeButton().querySelector(
  399. "tp-yt-paper-button#button"
  400. );
  401. let shortDislikeButton = getDislikeButton().querySelector(
  402. "tp-yt-paper-button#button"
  403. );
  404. if (shortLikeButton.getAttribute("aria-pressed") === "true") {
  405. shortLikeButton.style.color = getColorFromTheme(true);
  406. }
  407. if (shortDislikeButton.getAttribute("aria-pressed") === "true") {
  408. shortDislikeButton.style.color = getColorFromTheme(false);
  409. }
  410. mutationObserver.observer.observe(
  411. shortLikeButton,
  412. mutationObserver.options
  413. );
  414. mutationObserver.observer.observe(
  415. shortDislikeButton,
  416. mutationObserver.options
  417. );
  418. } else {
  419. getLikeButton().style.color = getColorFromTheme(true);
  420. getDislikeButton().style.color = getColorFromTheme(false);
  421. }
  422. }
  423. }
  424. });
  425. });
  426. }
  427.  
  428. function likeClicked() {
  429. if (checkForUserAvatarButton() == true) {
  430. if (previousState == 1) {
  431. likesvalue--;
  432. createRateBar(likesvalue, dislikesvalue);
  433. setDislikes(numberFormat(dislikesvalue));
  434. previousState = 3;
  435. } else if (previousState == 2) {
  436. likesvalue++;
  437. dislikesvalue--;
  438. setDislikes(numberFormat(dislikesvalue));
  439. createRateBar(likesvalue, dislikesvalue);
  440. previousState = 1;
  441. } else if (previousState == 3) {
  442. likesvalue++;
  443. createRateBar(likesvalue, dislikesvalue);
  444. previousState = 1;
  445. }
  446. if (extConfig.numberDisplayReformatLikes === true) {
  447. const nativeLikes = getLikeCountFromButton();
  448. if (nativeLikes !== false) {
  449. setLikes(numberFormat(nativeLikes));
  450. }
  451. }
  452. }
  453. }
  454.  
  455. function dislikeClicked() {
  456. if (checkForUserAvatarButton() == true) {
  457. if (previousState == 3) {
  458. dislikesvalue++;
  459. setDislikes(numberFormat(dislikesvalue));
  460. createRateBar(likesvalue, dislikesvalue);
  461. previousState = 2;
  462. } else if (previousState == 2) {
  463. dislikesvalue--;
  464. setDislikes(numberFormat(dislikesvalue));
  465. createRateBar(likesvalue, dislikesvalue);
  466. previousState = 3;
  467. } else if (previousState == 1) {
  468. likesvalue--;
  469. dislikesvalue++;
  470. setDislikes(numberFormat(dislikesvalue));
  471. createRateBar(likesvalue, dislikesvalue);
  472. previousState = 2;
  473. if (extConfig.numberDisplayReformatLikes === true) {
  474. const nativeLikes = getLikeCountFromButton();
  475. if (nativeLikes !== false) {
  476. setLikes(numberFormat(nativeLikes));
  477. }
  478. }
  479. }
  480. }
  481. }
  482.  
  483. function setInitialState() {
  484. setState();
  485. }
  486.  
  487. function getVideoId() {
  488. const urlObject = new URL(window.location.href);
  489. const pathname = urlObject.pathname;
  490. if (pathname.startsWith("/clip")) {
  491. return document.querySelector("meta[itemprop='videoId']").content;
  492. } else {
  493. if (pathname.startsWith("/shorts")) {
  494. return pathname.slice(8);
  495. }
  496. return urlObject.searchParams.get("v");
  497. }
  498. }
  499.  
  500. function isVideoLoaded() {
  501. if (isMobile) {
  502. return document.getElementById("player").getAttribute("loading") == "false";
  503. }
  504. const videoId = getVideoId();
  505.  
  506. return (
  507. document.querySelector(`ytd-watch-flexy[video-id='${videoId}']`) !== null
  508. );
  509. }
  510.  
  511. function roundDown(num) {
  512. if (num < 1000) return num;
  513. const int = Math.floor(Math.log10(num) - 2);
  514. const decimal = int + (int % 3 ? 1 : 0);
  515. const value = Math.floor(num / 10 ** decimal);
  516. return value * 10 ** decimal;
  517. }
  518.  
  519. function numberFormat(numberState) {
  520. let numberDisplay;
  521. if (extConfig.numberDisplayRoundDown === false) {
  522. numberDisplay = numberState;
  523. } else {
  524. numberDisplay = roundDown(numberState);
  525. }
  526. return getNumberFormatter(extConfig.numberDisplayFormat).format(
  527. numberDisplay
  528. );
  529. }
  530.  
  531. function getNumberFormatter(optionSelect) {
  532. let userLocales;
  533. if (document.documentElement.lang) {
  534. userLocales = document.documentElement.lang;
  535. } else if (navigator.language) {
  536. userLocales = navigator.language;
  537. } else {
  538. try {
  539. userLocales = new URL(
  540. Array.from(document.querySelectorAll("head > link[rel='search']"))
  541. ?.find((n) => n?.getAttribute("href")?.includes("?locale="))
  542. ?.getAttribute("href")
  543. )?.searchParams?.get("locale");
  544. } catch {
  545. cLog(
  546. "Cannot find browser locale. Use en as default for number formatting."
  547. );
  548. userLocales = "en";
  549. }
  550. }
  551.  
  552. let formatterNotation;
  553. let formatterCompactDisplay;
  554. switch (optionSelect) {
  555. case "compactLong":
  556. formatterNotation = "compact";
  557. formatterCompactDisplay = "long";
  558. break;
  559. case "standard":
  560. formatterNotation = "standard";
  561. formatterCompactDisplay = "short";
  562. break;
  563. case "compactShort":
  564. default:
  565. formatterNotation = "compact";
  566. formatterCompactDisplay = "short";
  567. }
  568.  
  569. const formatter = Intl.NumberFormat(userLocales, {
  570. notation: formatterNotation,
  571. compactDisplay: formatterCompactDisplay,
  572. });
  573. return formatter;
  574. }
  575.  
  576. function getColorFromTheme(voteIsLike) {
  577. let colorString;
  578. switch (extConfig.colorTheme) {
  579. case "accessible":
  580. if (voteIsLike === true) {
  581. colorString = "dodgerblue";
  582. } else {
  583. colorString = "gold";
  584. }
  585. break;
  586. case "neon":
  587. if (voteIsLike === true) {
  588. colorString = "aqua";
  589. } else {
  590. colorString = "magenta";
  591. }
  592. break;
  593. case "classic":
  594. default:
  595. if (voteIsLike === true) {
  596. colorString = "lime";
  597. } else {
  598. colorString = "red";
  599. }
  600. }
  601. return colorString;
  602. }
  603.  
  604. function setEventListeners(evt) {
  605. let jsInitChecktimer;
  606.  
  607. function checkForJS_Finish() {
  608. console.log();
  609. if (isShorts() || (getButtons()?.offsetParent && isVideoLoaded())) {
  610. const buttons = getButtons();
  611.  
  612. if (!window.returnDislikeButtonlistenersSet) {
  613. cLog("Registering button listeners...");
  614. try {
  615. buttons.children[0].addEventListener("click", likeClicked);
  616. buttons.children[1].addEventListener("click", dislikeClicked);
  617. buttons.children[0].addEventListener("touchstart", likeClicked);
  618. buttons.children[1].addEventListener("touchstart", dislikeClicked);
  619. } catch {
  620. return;
  621. } //Don't spam errors into the console
  622. window.returnDislikeButtonlistenersSet = true;
  623. }
  624. setInitialState();
  625. clearInterval(jsInitChecktimer);
  626. }
  627. }
  628.  
  629. cLog("Setting up...");
  630. jsInitChecktimer = setInterval(checkForJS_Finish, 111);
  631. }
  632.  
  633. (function () {
  634. "use strict";
  635. window.addEventListener("yt-navigate-finish", setEventListeners, true);
  636. setEventListeners();
  637. })();
  638. if (isMobile) {
  639. let originalPush = history.pushState;
  640. history.pushState = function (...args) {
  641. window.returnDislikeButtonlistenersSet = false;
  642. setEventListeners(args[2]);
  643. return originalPush.apply(history, args);
  644. };
  645. setInterval(() => {
  646. getDislikeButton().querySelector(".button-renderer-text").innerText =
  647. mobileDislikes;
  648. }, 1000);
  649. }

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址