Show Metacritic.com ratings

Show metacritic metascore and user ratings on: Bandcamp, Apple Itunes (Music), Amazon (Music,Movies,TV Shows), IMDb (Movies), Google Play (Music, Movies), Steam, Gamespot (PS4, XONE, PC), Rotten Tomatoes, Serienjunkies, BoxOfficeMojo, allmovie.com, fandango.com, Wikipedia (en), themoviedb.org, letterboxd, TVmaze, TVGuide, followshows.com, TheTVDB.com, ConsequenceOfSound, Pitchfork, Last.fm, TVnfo, rateyourmusic.com, GOG, Epic Games Store, save.tv, argenteam.net

目前为 2023-09-15 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Show Metacritic.com ratings
  3. // @description Show metacritic metascore and user ratings on: Bandcamp, Apple Itunes (Music), Amazon (Music,Movies,TV Shows), IMDb (Movies), Google Play (Music, Movies), Steam, Gamespot (PS4, XONE, PC), Rotten Tomatoes, Serienjunkies, BoxOfficeMojo, allmovie.com, fandango.com, Wikipedia (en), themoviedb.org, letterboxd, TVmaze, TVGuide, followshows.com, TheTVDB.com, ConsequenceOfSound, Pitchfork, Last.fm, TVnfo, rateyourmusic.com, GOG, Epic Games Store, save.tv, argenteam.net
  4. // @namespace cuzi
  5. // @icon https://www.metacritic.com/a/img/favicon.svg
  6. // @supportURL https://github.com/cvzi/Metacritic-userscript/issues
  7. // @contributionURL https://buymeacoff.ee/cuzi
  8. // @contributionURL https://ko-fi.com/cuzicvzi
  9. // @grant unsafeWindow
  10. // @grant GM.xmlHttpRequest
  11. // @grant GM.setValue
  12. // @grant GM.getValue
  13. // @grant GM.registerMenuCommand
  14. // @require https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js
  15. // @license GPL-3.0-or-later; https://www.gnu.org/licenses/gpl-3.0.txt
  16. // @antifeature tracking When a metacritic rating is displayed, we may store the url of the current website and the metacritic url in our database. Log files are temporarily retained by our database hoster Cloudflare Workers® and contain your IP address and browser configuration.
  17. // @version 92
  18. // @connect metacritic.com
  19. // @connect met.acritic.workers.dev
  20. // @connect imdb.com
  21. // @match https://*.bandcamp.com/*
  22. // @match https://play.google.com/store/music/album/*
  23. // @match https://play.google.com/store/movies/details/*
  24. // @match https://music.amazon.com/*
  25. // @match https://www.amazon.ca/*
  26. // @match https://www.amazon.co.jp/*
  27. // @match https://www.amazon.co.uk/*
  28. // @match https://smile.amazon.co.uk/*
  29. // @match https://www.amazon.com.au/*
  30. // @match https://www.amazon.com.mx/*
  31. // @match https://www.amazon.com/*
  32. // @match https://smile.amazon.com/*
  33. // @match https://www.amazon.de/*
  34. // @match https://smile.amazon.de/*
  35. // @match https://www.amazon.es/*
  36. // @match https://www.amazon.fr/*
  37. // @match https://www.amazon.in/*
  38. // @match https://www.amazon.it/*
  39. // @match https://www.imdb.com/title/*
  40. // @match https://store.steampowered.com/app/*
  41. // @match https://www.gamespot.com/*
  42. // @match https://www.serienjunkies.de/*
  43. // @match https://www.rottentomatoes.com/m/*
  44. // @match https://rottentomatoes.com/m/*
  45. // @match https://www.rottentomatoes.com/tv/*
  46. // @match https://rottentomatoes.com/tv/*
  47. // @match https://www.rottentomatoes.com/tv/*
  48. // @match https://rottentomatoes.com/tv/*
  49. // @match https://www.boxofficemojo.com/movies/*
  50. // @match https://www.boxofficemojo.com/release/*
  51. // @match https://www.allmovie.com/movie/*
  52. // @match https://en.wikipedia.org/*
  53. // @match https://www.fandango.com/*
  54. // @match https://www.flixster.com/movie/*
  55. // @match https://www.themoviedb.org/movie/*
  56. // @match https://www.themoviedb.org/tv/*
  57. // @match https://letterboxd.com/film/*
  58. // @match https://www.tvmaze.com/shows/*
  59. // @match https://www.tvguide.com/tvshows/*
  60. // @match https://followshows.com/show/*
  61. // @match https://thetvdb.com/series/*
  62. // @match https://thetvdb.com/movies/*
  63. // @match https://consequenceofsound.net/*
  64. // @match https://consequence.net/*
  65. // @match https://pitchfork.com/*
  66. // @match https://www.last.fm/*
  67. // @match https://tvnfo.com/s/*
  68. // @match https://rateyourmusic.com/release/album/*
  69. // @match https://open.spotify.com/*
  70. // @match https://play.spotify.com/album/*
  71. // @match https://www.nme.com/reviews/*
  72. // @match https://www.albumoftheyear.org/album/*
  73. // @match https://itunes.apple.com/*
  74. // @match https://music.apple.com/*
  75. // @match https://epguides.com/*
  76. // @match https://www.epguides.com/*
  77. // @match https://sharetv.com/shows/*
  78. // @match https://www.netflix.com/*
  79. // @match https://www.cc.com/*
  80. // @match https://www.tvhoard.com/*
  81. // @match https://www.amc.com/*
  82. // @match https://www.amcplus.com/*
  83. // @match https://comment.rlsbb.ru/*/
  84. // @match https://newalbumreleases.net/*
  85. // @match https://www.sho.com/*
  86. // @match https://www.epicgames.com/store/*
  87. // @match https://www.gog.com/*
  88. // @match https://www.allmusic.com/album/*
  89. // @match https://store.epicgames.com/*
  90. // @match https://www.steamgifts.com/giveaway/*
  91. // @match https://psa.pm/*
  92. // @match https://www.save.tv/*
  93. // @match https://argenteam.net/*
  94. // ==/UserScript==
  95.  
  96. /* globals alert, confirm, GM, DOMParser, $, Image, unsafeWindow, parent, Blob, failedImages */
  97.  
  98. const baseURL = 'https://www.metacritic.com/'
  99.  
  100. const baseURLmusic = 'https://www.metacritic.com/music/'
  101. const baseURLmovie = 'https://www.metacritic.com/movie/'
  102. const baseURLpcgame = 'https://www.metacritic.com/game/pc/'
  103. const baseURLps4 = 'https://www.metacritic.com/game/playstation-4/'
  104. const baseURLxone = 'https://www.metacritic.com/game/xbox-one/'
  105. const baseURLtv = 'https://www.metacritic.com/tv/'
  106.  
  107. const baseURLsearch = 'https://www.metacritic.com/search/{type}/{query}/results'
  108. const baseURLautosearch = 'https://www.metacritic.com/autosearch'
  109.  
  110. const baseURLdatabase = 'https://met.acritic.workers.dev/r.php'
  111. const baseURLwhitelist = 'https://met.acritic.workers.dev/whitelist.php'
  112. const baseURLblacklist = 'https://met.acritic.workers.dev/blacklist.php'
  113.  
  114. const TEMPORARY_BLACKLIST_TIMEOUT = 5 * 60
  115.  
  116. const windowPositions = [
  117. {
  118. bottom: 0,
  119. left: 0
  120. },
  121. {
  122. bottom: 0,
  123. right: 0
  124. },
  125. {
  126. top: 0,
  127. right: 0
  128. },
  129. {
  130. top: 0,
  131. left: 0
  132. }
  133. ]
  134.  
  135. // http://www.designcouch.com/home/why/2013/05/23/dead-simple-pure-css-loading-spinner/
  136. const CSS = '#mcdiv123 .grespinner{height:16px;width:16px;margin:0 auto;position:relative;animation:rotation .6s infinite linear;border-left:6px solid rgba(0,174,239,.15);border-right:6px solid rgba(0,174,239,.15);border-bottom:6px solid rgba(0,174,239,.15);border-top:6px solid rgba(0,174,239,.8);border-radius:100%}@keyframes rotation{from{transform:rotate(0)}to{transform:rotate(359deg)}}#mcdiv123searchresults .result{font:12px arial,helvetica,serif;border-top-width:1px;border-top-color:#ccc;border-top-style:solid;padding:5px}#mcdiv123searchresults .result .result_type{display:inline}#mcdiv123searchresults .result .result_wrap{float:left;width:100%}#mcdiv123searchresults .result .has_score{padding-left:42px}#mcdiv123searchresults .result .basic_stats{height:1%;overflow:hidden}#mcdiv123searchresults .result h3{font-size:14px;font-weight:700}#mcdiv123searchresults .result a{color:#09f;font-weight:700;text-decoration:none}#mcdiv123searchresults .metascore_w.game.seventyfive,#mcdiv123searchresults .metascore_w.positive,#mcdiv123searchresults .metascore_w.score_favorable,#mcdiv123searchresults .metascore_w.score_outstanding,#mcdiv123searchresults .metascore_w.sixtyone{background-color:#6c3}#mcdiv123searchresults .metascore_w.forty,#mcdiv123searchresults .metascore_w.game.fifty,#mcdiv123searchresults .metascore_w.mixed,#mcdiv123searchresults .metascore_w.score_mixed{background-color:#fc3}#mcdiv123searchresults .metascore_w.negative,#mcdiv123searchresults .metascore_w.score_terrible,#mcdiv123searchresults .metascore_w.score_unfavorable{background-color:red}#mcdiv123searchresults a.metascore_w,#mcdiv123searchresults span.metascore_w{display:inline-block}#mcdiv123searchresults .result .metascore_w{color:#fff!important;font-family:Arial,Helvetica,sans-serif;font-size:17px;font-style:normal!important;font-weight:700!important;height:2em;line-height:2em;text-align:center;vertical-align:middle;width:2em;float:left;margin:0 0 0 -42px}#mcdiv123searchresults .result .more_stats{font-size:10px;color:#444}#mcdiv123searchresults .result .release_date .data{font-weight:700;color:#000}#mcdiv123searchresults ol,#mcdiv123searchresults ul{list-style:none}#mcdiv123searchresults .result li.stat{background:0 0;display:inline;float:left;margin:0;padding:0 6px 0 0;white-space:nowrap}#mcdiv123searchresults .result .deck{margin:3px 0 0}#mcdiv123searchresults .result .basic_stat{display:inline;float:right;overflow:hidden;width:100%}'
  137.  
  138. let myDOMParser = null
  139. function domParser () {
  140. if (myDOMParser === null) {
  141. myDOMParser = new DOMParser()
  142. }
  143. return myDOMParser
  144. }
  145.  
  146. async function versionUpdate () {
  147. const version = parseInt(await GM.getValue('version', 0))
  148. if (version <= 91) {
  149. // Reset database
  150. await GM.setValue('map', '{}')
  151. await GM.setValue('black', '[]')
  152. await GM.setValue('hovercache', '{}')
  153. await GM.setValue('requestcache', '{}')
  154. await GM.setValue('searchcache', '{}')
  155. await GM.setValue('autosearchcache', '{}')
  156. await GM.setValue('temporaryblack', '{}')
  157. }
  158. if (version < 92) {
  159. await GM.setValue('version', 92)
  160. }
  161. }
  162.  
  163. async function acceptGDPR (showDialog) {
  164. if (showDialog === true) {
  165. await GM.setValue('gdpr', null)
  166. return acceptGDPR()
  167. }
  168. return new Promise(function (resolve) {
  169. GM.getValue('gdpr', null).then(function (value) {
  170. if (value === true) {
  171. return resolve(true)
  172. }
  173. if (value === false) {
  174. return resolve(false)
  175. }
  176. const html = '<h1>Privacy Policy for &quot;Show Metacritic.com ratings&quot;</h1><h2>General Data Protection Regulation (GDPR)</h2><p>We are a Data Controller of your information.</p> <p>&quot;Show Metacritic.com ratings&quot; legal basis for collecting and using the personal information described in this Privacy Policy depends on the Personal Information we collect and the specific context in which we collect the information:</p><ul> <li>&quot;Show Metacritic.com ratings&quot; needs to perform a contract with you</li> <li>You have given &quot;Show Metacritic.com ratings&quot; permission to do so</li> <li>Processing your personal information is in &quot;Show Metacritic.com ratings&quot; legitimate interests</li> <li>&quot;Show Metacritic.com ratings&quot; needs to comply with the law</li></ul> <p>&quot;Show Metacritic.com ratings&quot; will retain your personal information only for as long as is necessary for the purposes set out in this Privacy Policy. We will retain and use your information to the extent necessary to comply with our legal obligations, resolve disputes, and enforce our policies.</p> <p>If you are a resident of the European Economic Area (EEA), you have certain data protection rights. If you wish to be informed what Personal Information we hold about you and if you want it to be removed from our systems, please contact us. Our Privacy Policy was generated with the help of <a href="https://www.gdprprivacypolicy.net/">GDPR Privacy Policy Generator</a> and the <a href="https://www.app-privacy-policy.com">App Privacy Policy Generator</a>.</p><p>In certain circumstances, you have the following data protection rights:</p><ul> <li>The right to access, update or to delete the information we have on you.</li> <li>The right of rectification.</li> <li>The right to object.</li> <li>The right of restriction.</li> <li>The right to data portability</li> <li>The right to withdraw consent</li></ul><h2>Log Files</h2><p>&quot;Show Metacritic.com ratings&quot; follows a standard procedure of using log files. These files log visitors when they visit websites. All hosting companies do this and a part of hosting services\' analytics. The information collected by log files include internet protocol (IP) addresses, browser type, Internet Service Provider (ISP), date and time stamp, referring/exit pages, and possibly the number of clicks. These are not linked to any information that is personally identifiable. The purpose of the information is for analyzing trends, administering the site, tracking users\' movement on the website, and gathering demographic information.</p><h2>Privacy Policies</h2><P>You may consult this list to find the Privacy Policy for each of the advertising partners of &quot;Show Metacritic.com ratings&quot;.</p><p>Third-party ad servers or ad networks uses technologies like cookies, JavaScript, or Web Beacons that are used in their respective advertisements and links that appear on &quot;Show Metacritic.com ratings&quot;, which are sent directly to users\' browser. They automatically receive your IP address when this occurs. These technologies are used to measure the effectiveness of their advertising campaigns and/or to personalize the advertising content that you see on websites that you visit.</p><p>Note that &quot;Show Metacritic.com ratings&quot; has no access to or control over these cookies that are used by third-party advertisers.</p><h2>Third Party Privacy Policies</h2><p>&quot;Show Metacritic.com ratings&quot;\'s Privacy Policy does not apply to other advertisers or websites. Thus, we are advising you to consult the respective Privacy Policies of these third-party ad servers for more detailed information. It may include their practices and instructions about how to opt-out of certain options.List of these Privacy Policies and their links: <ul> <li>Cloudflare Workers®: <a href="https://www.cloudflare.com/privacypolicy/">https://www.cloudflare.com/privacypolicy/</a></li> <li>www.metacritic.com: <a href="https://privacy.cbs/">https://privacy.cbs/</a></li></ul></p><p>You can choose to disable cookies through your individual browser options.</p><h2>Children\'s Information</h2><p>Another part of our priority is adding protection for children while using the internet. We encourage parents and guardians to observe, participate in, and/or monitor and guide their online activity.</p><p>&quot;Show Metacritic.com ratings&quot; does not knowingly collect any Personal Identifiable Information from children under the age of 13. If you think that your child provided this kind of information on our website, we strongly encourage you to contact us immediately and we will do our best efforts to promptly remove such information from our records.</p><h2>Online Privacy Policy Only</h2><p>Our Privacy Policy created at GDPRPrivacyPolicy.net) applies only to our online activities and is valid for users of our program with regards to the information that they shared and/or collect in &quot;Show Metacritic.com ratings&quot;. This policy is not applicable to any information collected offline or via channels other than this program. <a href="https://gdprprivacypolicy.net">Our GDPR Privacy Policy</a> was generated from the GDPR Privacy Policy Generator.</p><h2>Contact</h2><p>Contact us via github <a href="https://github.com/cvzi/Metacritic-userscript">https://github.com/cvzi/Metacritic-userscript</a> or email cuzi@openmail.cc</p><h2>Consent</h2><p>By using our program ("userscript"), you hereby consent to our Privacy Policy and agree to its terms.</p>'
  177. const div = document.body.appendChild(document.createElement('div'))
  178. div.innerHTML = html
  179. div.style = 'z-index:9999;position:absolute;min-height:100%;top:0px; left:0px; right:0px; padding:10px; background:white; color:black; font-family:serif; font-size:16px'
  180. div.appendChild(document.createElement('br'))
  181. const acceptButton = div.appendChild(document.createElement('button'))
  182. acceptButton.setAttribute('style', 'color:black;background:#e5e4e4;border:2px #bbb outset;margin:5px;padding:2px 10px;font-size:16px;font-family:sans-serif;cursor:pointer')
  183. acceptButton.appendChild(document.createTextNode('Accept'))
  184. acceptButton.addEventListener('click', function () {
  185. div.remove()
  186. resolve(true)
  187. GM.setValue('gdpr', true)
  188. })
  189. const declineButton = div.appendChild(document.createElement('button'))
  190. declineButton.setAttribute('style', 'color:black;background:#e5e4e4;border:2px #bbb outset;margin:5px;padding:2px 10px;font-size:16px;font-family:sans-serif;cursor:pointer')
  191. declineButton.appendChild(document.createTextNode('Decline'))
  192. declineButton.addEventListener('click', function () {
  193. alert('You may uninstall the userscript now.')
  194. div.remove()
  195. resolve(false)
  196. GM.setValue('gdpr', false)
  197. })
  198. const space = div.appendChild(document.createElement('div'))
  199. space.style = 'height:2000px;'
  200. div.scrollIntoView()
  201. window.setTimeout(function () {
  202. alert('ShowMetacriticRatings:\n\nWhen you use this script, data will be sent to our database and to metacritic.com. This data includes the url of the website that you are browsing, the metacritic page url, your IP adress, browser configuration and language preferences. We only store the url of the website and the metacritic url and no personal information. Log files are temporarily retained and contain your IP address. We have no control over which data is stored by metacritic.com and our hoster heroku.com, see their respective privacy policies for more information (see "Third Party Privacy Policies").\n\nPlease read and accept our privacy policy now or uninstall this userscript.')
  203. }, 20)
  204. })
  205. })
  206. }
  207.  
  208. function delay (ms) {
  209. return new Promise(function (resolve) {
  210. window.setTimeout(() => resolve(), ms)
  211. })
  212. }
  213.  
  214. function getHostname (url) {
  215. const a = document.createElement('a')
  216. a.href = url
  217. return a.hostname
  218. }
  219. function absoluteMetaURL (url) {
  220. if (url.startsWith('https://')) {
  221. return url
  222. }
  223. if (url.startsWith('http://')) {
  224. return 'https' + url.substr(4)
  225. }
  226. if (url.startsWith('//')) {
  227. return baseURL + url.substr(2)
  228. }
  229. if (url.startsWith('/')) {
  230. return baseURL + url.substr(1)
  231. }
  232. return baseURL + url
  233. }
  234.  
  235. const parseLDJSONCache = {}
  236. function parseLDJSON (keys, condition) {
  237. if (document.querySelector('script[type="application/ld+json"]')) {
  238. const xmlEntitiesElement = document.createElement('div')
  239. const xmlEntitiesPattern = /&(?:#x[a-f0-9]+|#[0-9]+|[a-z0-9]+);?/ig
  240. const xmlEntities = function (s) {
  241. s = s.replace(xmlEntitiesPattern, (m) => {
  242. xmlEntitiesElement.innerHTML = m
  243. return xmlEntitiesElement.textContent
  244. })
  245. return s
  246. }
  247. const decodeXmlEntities = function (jsonObj) {
  248. // Traverse through object, decoding all strings
  249. if (jsonObj !== null && typeof jsonObj === 'object') {
  250. Object.entries(jsonObj).forEach(([key, value]) => {
  251. // key is either an array index or object key
  252. jsonObj[key] = decodeXmlEntities(value)
  253. })
  254. } else if (typeof jsonObj === 'string') {
  255. return xmlEntities(jsonObj)
  256. }
  257. return jsonObj
  258. }
  259.  
  260. const data = []
  261. const scripts = document.querySelectorAll('script[type="application/ld+json"]')
  262. for (let i = 0; i < scripts.length; i++) {
  263. let jsonld
  264. if (scripts[i].innerText in parseLDJSONCache) {
  265. jsonld = parseLDJSONCache[scripts[i].innerText]
  266. } else {
  267. try {
  268. jsonld = JSON.parse(scripts[i].innerText)
  269. parseLDJSONCache[scripts[i].innerText] = jsonld
  270. } catch (e) {
  271. parseLDJSONCache[scripts[i].innerText] = null
  272. continue
  273. }
  274. }
  275. if (jsonld) {
  276. if (Array.isArray(jsonld)) {
  277. data.push(...jsonld)
  278. } else {
  279. data.push(jsonld)
  280. }
  281. }
  282. }
  283. for (let i = 0; i < data.length; i++) {
  284. try {
  285. if (data[i] && data[i] && (typeof condition !== 'function' || condition(data[i]))) {
  286. if (Array.isArray(keys)) {
  287. const r = []
  288. for (let j = 0; j < keys.length; j++) {
  289. r.push(data[i][keys[j]])
  290. }
  291. return decodeXmlEntities(r)
  292. } else if (keys) {
  293. return decodeXmlEntities(data[i][keys])
  294. } else if (typeof condition === 'function') {
  295. return decodeXmlEntities(data[i]) // Return whole object
  296. }
  297. }
  298. } catch (e) {
  299. continue
  300. }
  301. }
  302. return decodeXmlEntities(data)
  303. }
  304. return null
  305. }
  306.  
  307. function name2metacritic (s) {
  308. const mc = s.normalize('NFKD').replace(/\//g, '').replace(/[\u0300-\u036F]/g, '').replace(/&/g, 'and').replace(/\W+/g, ' ').toLowerCase().trim().replace(/\W+/g, '-')
  309. if (!mc) {
  310. throw new Error("name2metacritic converted '" + s + "' to empty string")
  311. }
  312. return mc
  313. }
  314. function minutesSince (time) {
  315. const seconds = ((new Date()).getTime() - time.getTime()) / 1000
  316. return seconds > 60 ? parseInt(seconds / 60) + ' min ago' : 'now'
  317. }
  318. function randomStringId () {
  319. const id10 = () => Math.floor((1 + Math.random()) * 0x10000000000).toString(16).substring(1)
  320. return id10() + id10() + id10() + id10() + id10() + id10()
  321. }
  322. function fixMetacriticURLs (html) {
  323. return html.replace(/<a /g, '<a target="_blank" ').replace(/href="\//g, 'href="' + baseURL).replace(/src="\//g, 'src="' + baseURL)
  324. }
  325. function searchType2metacritic (type) {
  326. return ({
  327. movie: 'movie',
  328. pcgame: 'game',
  329. xonegame: 'game',
  330. ps4game: 'game',
  331. music: 'album',
  332. tv: 'tv'
  333. })[type]
  334. }
  335. function metacritic2searchType (type) {
  336. return ({
  337. Album: 'music',
  338. TV: 'tv',
  339. Movie: 'movie',
  340. 'PC Game': 'pcgame',
  341. 'PS4 Game': 'ps4game',
  342. 'XONE Game': 'onegame',
  343. 'WIIU Game': 'xxxxx',
  344. '3DS Game': 'xxxx'
  345. })[type]
  346. }
  347.  
  348. function replaceBrackets (str) {
  349. str = str.replace(/\([^(]*\)/g, '')
  350. str = str.replace(/\[[^\]]*\]/g, '')
  351. return str.trim()
  352. }
  353. function removeSymbols (str) {
  354. str = str.replace(/[^\s0-9A-Za-zÀ-ÖØ-öø-ÿ]*/gi, '').trim()
  355. return str.trim()
  356. }
  357. const dashRegExp = /[-\u2010\u2011\u2012\u2013\u2014\u2015\uFE58\uFE63\uFF0D]/
  358. function removeAnythingAfterDash (str) {
  359. str = str.split(dashRegExp)[0]
  360. return str.trim()
  361. }
  362.  
  363. function broadenSearch (data, step, type) {
  364. if (type === 'pcgame') {
  365. if (step > 0) {
  366. data[0] = replaceBrackets(data[0])
  367. } else if (step > 1) {
  368. data[0] = removeSymbols(data[0])
  369. } else if (step > 2) {
  370. data[0] = removeAnythingAfterDash(data[0])
  371. }
  372. }
  373. return data
  374. }
  375.  
  376. function balloonAlert (message, timeout, title, css, click) {
  377. let header
  378. if (title) {
  379. header = '<div style="background:rgb(220,230,150); padding: 2px 12px;">' + title + '</div>'
  380. } else if (title === false) {
  381. header = ''
  382. } else {
  383. header = '<div style="background:rgb(220,230,150); padding: 2px 12px;">Userscript alert</div>'
  384. }
  385. const div = $('<div>' + header + '<div style="padding:5px">' + message.split('\n').join('<br>') + '</div></div>')
  386. div.css({
  387. position: 'fixed',
  388. top: 10,
  389. left: 10,
  390. maxWidth: 200,
  391. zIndex: '2147483601',
  392. background: 'rgb(240,240,240)',
  393. border: '2px solid yellow',
  394. borderRadius: '6px',
  395. boxShadow: '0 0 3px 3px rgba(100, 100, 100, 0.2)',
  396. fontFamily: 'sans-serif',
  397. color: 'black'
  398. })
  399. if (css) {
  400. div.css(css)
  401. }
  402. div.appendTo(document.body)
  403.  
  404. if (click) {
  405. div.click(function (ev) {
  406. $(this).hide(500)
  407. click.call(this, ev)
  408. })
  409. }
  410.  
  411. if (!click) {
  412. const close = $('<div title="Close" style="cursor:pointer; position:absolute; top:0px; right:3px;">&#10062;</div>').appendTo(div)
  413. close.click(function () {
  414. $(this.parentNode).hide(1000)
  415. })
  416. }
  417.  
  418. if (timeout && timeout > 0) {
  419. window.setTimeout(function () {
  420. div.hide(3000)
  421. }, timeout)
  422. }
  423. return div
  424. }
  425.  
  426. function filterUniversalUrl (url) {
  427. try {
  428. url = url.match(/http.+/)[0]
  429. } catch (e) { }
  430.  
  431. try {
  432. url = url.replace(/https?:\/\/(www.)?/, '')
  433. } catch (e) { }
  434.  
  435. if (url.indexOf('#') !== -1) {
  436. url = url.split('#')[0]
  437. }
  438.  
  439. if (url.startsWith('imdb.com/') && url.match(/(imdb\.com\/\w+\/\w+\/)/)) {
  440. // Remove movie subpage from imdb url
  441. return url.match(/(imdb\.com\/\w+\/\w+\/)/)[1]
  442. } else if (url.startsWith('boxofficemojo.com/') && url.indexOf('id=') !== -1) {
  443. // Keep the important id= on
  444. try {
  445. const parts = url.split('?')
  446. const page = parts[0] + '?'
  447. const idparam = parts[1].match(/(id=.+?)(\.|&)/)[1]
  448. return page + idparam
  449. } catch (e) {
  450. return url
  451. }
  452. } else {
  453. // Default: Remove parameters
  454. return url.split('?')[0].split('&')[0]
  455. }
  456. }
  457.  
  458. async function addToMap (url, metaurl) {
  459. const data = JSON.parse(await GM.getValue('map', '{}'))
  460.  
  461. url = filterUniversalUrl(url)
  462. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  463.  
  464. data[url] = metaurl
  465.  
  466. await GM.setValue('map', JSON.stringify(data));
  467.  
  468. (new Image()).src = baseURLwhitelist + '?docurl=' + encodeURIComponent(url) + '&metaurl=' + encodeURIComponent(metaurl) + '&ref=' + encodeURIComponent(randomStringId())
  469. return [url, metaurl]
  470. }
  471.  
  472. async function removeFromMap (url) {
  473. const data = JSON.parse(await GM.getValue('map', '{}'))
  474.  
  475. url = filterUniversalUrl(url)
  476. if (url in data) {
  477. delete data[url]
  478. await GM.setValue('map', JSON.stringify(data))
  479. }
  480. }
  481.  
  482. async function addToTemporaryBlacklist (metaurl) {
  483. const data = JSON.parse(await GM.getValue('temporaryblack', '{}'))
  484.  
  485. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  486. metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/')
  487. metaurl = metaurl.replace(/^\/+/, '')
  488.  
  489. data[metaurl] = (new Date()).toJSON()
  490.  
  491. // Remove old entries
  492. const now = (new Date()).getTime()
  493. const timeout = TEMPORARY_BLACKLIST_TIMEOUT * 1000
  494. for (const prop in data) {
  495. if (now - (new Date(data[prop].time)).getTime() > timeout) {
  496. delete data[prop]
  497. }
  498. }
  499.  
  500. await GM.setValue('temporaryblack', JSON.stringify(data))
  501.  
  502. return true
  503. }
  504.  
  505. async function isTemporaryBlacklisted (metaurl) {
  506. const data = JSON.parse(await GM.getValue('temporaryblack', '{}'))
  507.  
  508. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  509. metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/')
  510. metaurl = metaurl.replace(/^\/+/, '')
  511.  
  512. if (metaurl in data) {
  513. const now = (new Date()).getTime()
  514. const timeout = TEMPORARY_BLACKLIST_TIMEOUT * 1000
  515. if (now - (new Date(data[metaurl])).getTime() < timeout) {
  516. return true
  517. }
  518. }
  519. return false
  520. }
  521.  
  522. async function addToBlacklist (url, metaurl) {
  523. const data = JSON.parse(await GM.getValue('black', '[]'))
  524.  
  525. url = filterUniversalUrl(url)
  526. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  527.  
  528. data.push([url, metaurl])
  529.  
  530. await GM.setValue('black', JSON.stringify(data));
  531.  
  532. (new Image()).src = baseURLblacklist + '?docurl=' + encodeURIComponent(url) + '&metaurl=' + encodeURIComponent(metaurl) + '&ref=' + encodeURIComponent(randomStringId())
  533. return [url, metaurl]
  534. }
  535.  
  536. async function removeFromBlacklist (docurl, metaurl) {
  537. docurl = filterUniversalUrl(docurl)
  538. docurl = docurl.replace(/https?:\/\/(www.)?/, '')
  539.  
  540. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  541. metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/') // remove double slash
  542. metaurl = metaurl.replace(/^\/+/, '') // remove starting slash
  543.  
  544. const data = JSON.parse(await GM.getValue('black', '[]')) // [ [docurl0, metaurl0] , [docurl1, metaurl1] , ... ]
  545. const found = []
  546. for (let i = 0; i < data.length; i++) {
  547. if (data[i][0] === docurl && data[i][1] === metaurl) {
  548. found.push(i)
  549. }
  550. }
  551. for (let i = found.length - 1; i >= 0; i--) {
  552. data.pop(i)
  553. }
  554.  
  555. await GM.setValue('black', JSON.stringify(data))
  556. }
  557.  
  558. async function isBlacklistedUrl (docurl, metaurl) {
  559. docurl = filterUniversalUrl(docurl)
  560. docurl = docurl.replace(/https?:\/\/(www.)?/, '')
  561.  
  562. metaurl = metaurl.replace(/^https?:\/\/(www.)?metacritic\.com\//, '')
  563. metaurl = metaurl.replace(/\/\//g, '/').replace(/\/\//g, '/') // remove double slash
  564. metaurl = metaurl.replace(/^\/+/, '') // remove starting slash
  565.  
  566. const data = JSON.parse(await GM.getValue('black', '[]')) // [ [docurl0, metaurl0] , [docurl1, metaurl1] , ... ]
  567. for (let i = 0; i < data.length; i++) {
  568. if (data[i][0] === docurl && data[i][1] === metaurl) {
  569. return true
  570. }
  571. }
  572. return false
  573. }
  574.  
  575. let listenForHotkeysActive = false
  576. function listenForHotkeys (code, cb) {
  577. // Call cb() as soon as the code sequence was typed
  578. if (listenForHotkeysActive) {
  579. return
  580. }
  581. listenForHotkeysActive = true
  582. let i = 0
  583. $(document).bind('keydown.listenForHotkeys', function (ev) {
  584. if (document.activeElement === document.body) {
  585. if (ev.key !== code[i]) {
  586. i = 0
  587. } else {
  588. i++
  589. if (i === code.length) {
  590. ev.preventDefault()
  591. $(document).unbind('keydown.listenForHotkeys')
  592. cb()
  593. }
  594. }
  595. }
  596. })
  597. }
  598.  
  599. function waitForHotkeysMETA () {
  600. listenForHotkeys('meta', (ev) => openSearchBox())
  601. }
  602.  
  603. async function handleJSONredirect (response) {
  604. let blacklistedredirect = false
  605. const j = JSON.parse(response.responseText)
  606.  
  607. // Blacklist items from database received?
  608. if ('blacklist' in j && j.blacklist && j.blacklist.length) {
  609. // Save new blacklist items
  610. const data = JSON.parse(await GM.getValue('black', '[]'))
  611. for (let i = 0; i < j.blacklist.length; i++) {
  612. const saveDocurl = j.blacklist[i].docurl
  613. const saveMetaurl = j.blacklist[i].metaurl
  614.  
  615. data.push([saveDocurl, saveMetaurl])
  616. if (j.jsonRedirect === '/' + saveMetaurl) {
  617. // Redirect is blacklisted!
  618. blacklistedredirect = true
  619. }
  620. }
  621. await GM.setValue('black', JSON.stringify(data))
  622. }
  623. if (blacklistedredirect) {
  624. // Redirect was blacklisted, show nothing
  625. console.debug('ShowMetacriticRatings: Redirect was blacklisted -> show nothing')
  626. return null
  627. } else {
  628. // Load redirect
  629. current.metaurl = absoluteMetaURL(j.jsonRedirect)
  630. response = await asyncRequest({
  631. url: current.metaurl
  632. }).catch(function (response) {
  633. console.error('ShowMetacriticRatings: Error 01')
  634. })
  635. return response
  636. }
  637. }
  638.  
  639. function extractHoverFromFullPage (response) {
  640. let html = 'ShowMetacriticRatings:<br>Error occured in extractHoverFromFullPage()'
  641. try {
  642. // Try parsing HTML
  643. const doc = domParser().parseFromString(response.responseText, 'text/html')
  644.  
  645. const content = Array.from(doc.querySelectorAll('.c-reviewsSection_carouselContainer .c-reviewsOverview_overviewDetails')).map(e => e.outerHTML).join('\n\n')
  646.  
  647. html = `
  648. <div id="hover_div_a20230915">
  649.  
  650. ${content}
  651.  
  652. </div>
  653. `
  654. } catch (e) {
  655. console.warn('ShowMetacriticRatings: Error parsing HTML: ' + e)
  656. // fallback to cutting out the relevant parts
  657. const parts = response.responseText.split('c-productHero_score-container')
  658.  
  659. html = '<div class="' + parts[1].split('c-ratingReviewWrapper')[0] + '"></div></div>'
  660. if (html.length > 5000) {
  661. // Probably something went wrong, let's cut the response to prevent too long content
  662. console.warn('ShowMetacriticRatings: Cutting response to 5000 chars')
  663. html = html.substring(0, 5000)
  664. }
  665. }
  666. return html
  667. }
  668.  
  669. function asyncRequest (data) {
  670. return new Promise(function (resolve, reject) {
  671. isInRequestCache(data).then(function (cachedValue) {
  672. if (cachedValue) {
  673. return window.setTimeout(() => resolve(cachedValue), 10)
  674. }
  675. const defaultHeaders = {
  676. Referer: data.url,
  677. // Host: getHostname(data.url),
  678. 'User-Agent': navigator.userAgent
  679. }
  680. const defaultData = {
  681. method: 'GET',
  682. onload: function (response) {
  683. storeInRequestCache(data, response)
  684. resolve(response)
  685. },
  686. onerror: (response) => reject(response)
  687. }
  688. if ('headers' in data) {
  689. data.headers = Object.assign(defaultHeaders, data.headers)
  690. } else {
  691. data.headers = defaultHeaders
  692. }
  693. data = Object.assign(defaultData, data)
  694. GM.xmlHttpRequest(data)
  695. })
  696. })
  697. }
  698.  
  699. async function storeInRequestCache (requestData, response) {
  700. const newkey = JSON.stringify({
  701. url: requestData.url,
  702. method: requestData.method || 'GET',
  703. data: requestData.data || null
  704. })
  705. const cache = JSON.parse(await GM.getValue('requestcache', '{}'))
  706. const now = (new Date()).getTime()
  707. const timeout = 15 * 60 * 1000
  708. for (const prop in cache) {
  709. // Delete cached values, that are older than 15 minutes
  710. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  711. delete cache[prop]
  712. }
  713. }
  714.  
  715. const newobj = {}
  716. for (const key in response) {
  717. newobj[key] = response[key]
  718. }
  719. newobj.responseText = '' + response.responseText
  720. newobj.cached = true
  721. if (!('time' in newobj)) {
  722. newobj.time = (new Date()).toJSON()
  723. }
  724.  
  725. cache[newkey] = newobj
  726.  
  727. await GM.setValue('requestcache', JSON.stringify(cache))
  728. }
  729.  
  730. async function isInRequestCache (requestData) {
  731. const key = JSON.stringify({
  732. url: requestData.url,
  733. method: requestData.method || 'GET',
  734. data: requestData.data || null
  735. })
  736.  
  737. const cache = JSON.parse(await GM.getValue('requestcache', '{}'))
  738. const now = (new Date()).getTime()
  739. const timeout = 15 * 60 * 1000
  740. for (const prop in cache) {
  741. // Delete cached values, that are older than 15 minutes
  742. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  743. delete cache[prop]
  744. }
  745. }
  746.  
  747. if (key in cache) {
  748. return cache[key]
  749. } else {
  750. return false
  751. }
  752. }
  753.  
  754. async function storeInHoverCache (metaurl, response, orgMetaUrl) {
  755. const cache = JSON.parse(await GM.getValue('hovercache', '{}'))
  756. const now = (new Date()).getTime()
  757. const timeout = 2 * 60 * 60 * 1000
  758. for (const prop in cache) {
  759. // Delete cached values, that are older than 2 hours
  760. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  761. delete cache[prop]
  762. }
  763. }
  764.  
  765. const newobj = {}
  766. for (const key in response) {
  767. newobj[key] = response[key]
  768. }
  769. newobj.responseText = '' + response.responseText
  770. newobj.cached = true
  771. if (!('time' in newobj)) {
  772. newobj.time = (new Date()).toJSON()
  773. }
  774.  
  775. cache[metaurl] = newobj
  776. if (orgMetaUrl && orgMetaUrl !== metaurl) { // Store redirect
  777. cache[orgMetaUrl] = { time: (new Date()).toJSON(), redirect: metaurl }
  778. }
  779.  
  780. await GM.setValue('hovercache', JSON.stringify(cache))
  781. }
  782.  
  783. async function isInHoverCache (metaurl) {
  784. const cache = JSON.parse(await GM.getValue('hovercache', '{}'))
  785. const now = (new Date()).getTime()
  786. const timeout = 2 * 60 * 60 * 1000
  787. for (const prop in cache) {
  788. // Delete cached values, that are older than 2 hours
  789. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  790. delete cache[prop]
  791. }
  792. }
  793.  
  794. function resolveRedirects (cacheEntry) {
  795. if (cacheEntry.redirect) {
  796. const newkey = cacheEntry.redirect
  797. if (newkey in cache) {
  798. const value = cache[newkey]
  799. delete cache[newkey]
  800. return resolveRedirects(value)
  801. }
  802. } else {
  803. return cacheEntry
  804. }
  805. return false
  806. }
  807.  
  808. if (metaurl in cache) {
  809. const value = cache[metaurl]
  810. delete cache[metaurl]
  811. return resolveRedirects(value)
  812. } else {
  813. return false
  814. }
  815. }
  816.  
  817. async function loadHoverInfo () {
  818. const cacheResponse = await isInHoverCache(current.metaurl)
  819. if (cacheResponse !== false) {
  820. console.debug(`ShowMetacriticRatings: loadHoverInfo () ${current.metaurl} found in hover cache`)
  821. if (cacheResponse.responseText.indexOf('"jsonRedirect"') !== -1) {
  822. return await handleJSONredirect(cacheResponse)
  823. }
  824. return cacheResponse
  825. }
  826. const requestURL = baseURLdatabase
  827. const requestParams = 'm=' + encodeURIComponent(current.docurl) + '&a=' + encodeURIComponent(current.metaurl)
  828.  
  829. let response = await asyncRequest({
  830. method: 'POST',
  831. url: requestURL,
  832. data: requestParams,
  833. headers: {
  834. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  835. }
  836. }).catch(function (response) {
  837. console.warn('ShowMetacriticRatings: Error 02\nurl=' + requestURL + '\nparams=' + requestParams + '\nstatus=' + response.status)
  838. })
  839.  
  840. if (response.responseText && response.responseText.indexOf('"jsonRedirect"') !== -1) {
  841. response = await handleJSONredirect(response)
  842. }
  843.  
  844. if (response.status >= 500) {
  845. // Metacritic server error, try again after 2 seconds
  846. console.warn('ShowMetacriticRatings: Metacritic server error\nwait 2s for retry\nurl=' + current.metaurl + '\nstatus=' + response.status)
  847. await delay(2000)
  848. response = await asyncRequest({ url: current.metaurl }).catch(function (response) {
  849. console.warn('ShowMetacriticRatings: Error 06\nurl=' + current.metaurl + '\nstatus=' + response.status)
  850. })
  851. if (response.status > 300) {
  852. console.warn('ShowMetacriticRatings: Metacritic server error. Error 07. Retry failed as well.\nurl=' + current.metaurl + '\nstatus=' + response.status)
  853. } else {
  854. const newobj = {}
  855. for (const key in response) {
  856. newobj[key] = response[key]
  857. }
  858. newobj.responseText = extractHoverFromFullPage(response)
  859. response = newobj
  860. }
  861. }
  862.  
  863. // Extract relevant data from HTMl
  864. const newobj = {}
  865. for (const key in response) {
  866. newobj[key] = response[key]
  867. }
  868. newobj.responseText = extractHoverFromFullPage(response)
  869. response = newobj
  870.  
  871. if (!('time' in response)) {
  872. response.time = (new Date()).toJSON()
  873. }
  874. if (response.status === 200 && response.responseText) {
  875. return response
  876. } else {
  877. const error = new Error('ShowMetacriticRatings: loadHoverInfo()\nUrl: ' + response.finalUrl + '\nStatus: ' + response.status)
  878. error.status = response.status
  879. error.responseText = response.responseText
  880. throw error
  881. }
  882. }
  883.  
  884. function changePosition () {
  885. // Cycle through positions
  886. GM.getValue('position', JSON.stringify(windowPositions[0])).then(function (s) {
  887. let index
  888. for (index = 0; index < windowPositions.length; index++) {
  889. if (JSON.stringify(windowPositions[index]) === s) {
  890. break
  891. }
  892. }
  893. const nextIndex = (index + 1) % windowPositions.length
  894. GM.setValue('position', JSON.stringify(windowPositions[nextIndex])).then(function () {
  895. document.location.reload()
  896. })
  897. })
  898. }
  899.  
  900. const current = {
  901. metaurl: false,
  902. docurl: false,
  903. type: false,
  904. data: [], // Array of raw search keys
  905. searchTerm: false,
  906. product: null,
  907. broadenCounter: 0
  908. }
  909.  
  910. async function loadMetacriticUrl (fromSearch) {
  911. if (!current.metaurl) {
  912. alert('ShowMetacriticRatings: Error 04')
  913. return
  914. }
  915. const orgMetaUrl = current.metaurl
  916. if (await isBlacklistedUrl(document.location.href, current.metaurl)) {
  917. waitForHotkeysMETA()
  918. return
  919. }
  920.  
  921. if (await isTemporaryBlacklisted(current.metaurl)) {
  922. console.debug(`ShowMetacriticRatings: loadMetacriticUrl(fromSearch=${fromSearch}) ${current.metaurl} is temporary blacklisted`)
  923. waitForHotkeysMETA()
  924. return
  925. }
  926.  
  927. const response = await loadHoverInfo().catch(async function (response) {
  928. if (response instanceof Error || (response && response.stack && response.message)) {
  929. if (!fromSearch && ('status' in response && response.status === 404)) {
  930. console.debug('ShowMetacriticRatings: loadMetacriticUrl(): status=404')
  931. // No results
  932. let broadenFct = broadenSearch // global broadenSearch function is the default
  933. if ('broaden' in current.product) {
  934. // try product 'broaden'-function if it is defined
  935. broadenFct = current.product.broaden
  936. }
  937. const newData = await broadenFct(current.data.slice(0), ++current.broadenCounter, current.type)
  938. if (JSON.stringify(newData) !== JSON.stringify(current.data)) {
  939. current.data = newData
  940. metacritic[current.type](current.docurl, current.product, ...newData)
  941. } else if (JSON.stringify(newData) === JSON.stringify(current.data)) {
  942. // Same data as before, try once again to broaden
  943. const newData2 = await broadenFct(current.data.slice(0), ++current.broadenCounter, current.type)
  944. if (JSON.stringify(newData2) !== JSON.stringify(current.data)) {
  945. current.data = newData2
  946. metacritic[current.type](current.docurl, current.product, ...newData2)
  947. } else {
  948. console.debug('ShowMetacriticRatings: loadMetacriticUrl(): ' + ('broaden' in current.product ? 'product specific' : 'global') + " 'broaden search' did not change after " + current.broadenCounter + ' steps')
  949. }
  950. } else {
  951. console.debug("ShowMetacriticRatings: loadMetacriticUrl(): Unexpected result from 'broaden'-function: ", newData)
  952. }
  953. } else {
  954. console.error(`ShowMetacriticRatings: loadMetacriticUrl(fromSearch=${fromSearch}) current.metaurl = ${current.metaurl}. Error in loadHoverInfo():\n`, response)
  955. }
  956. }
  957.  
  958. if (fromSearch) {
  959. startSearch()
  960. }
  961. })
  962.  
  963. if (await isBlacklistedUrl(document.location.href, current.metaurl)) {
  964. waitForHotkeysMETA()
  965. return
  966. }
  967.  
  968. if (typeof response !== 'undefined') {
  969. showHoverInfo(response, orgMetaUrl)
  970. } else {
  971. waitForHotkeysMETA()
  972. }
  973. }
  974.  
  975. async function startSearch () {
  976. waitForHotkeysMETA()
  977.  
  978. const cache = JSON.parse(await GM.getValue('autosearchcache', '{}'))
  979. const now = (new Date()).getTime()
  980. const timeout = 2 * 60 * 60 * 1000
  981. for (const prop in cache) {
  982. // Delete cached values, that are older than 2 hours
  983. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  984. delete cache[prop]
  985. }
  986. }
  987.  
  988. if (current.type === 'music') {
  989. current.searchTerm = current.data[0]
  990. } else {
  991. current.searchTerm = current.data.join(' ')
  992. }
  993. let response
  994. if (current.searchTerm in cache) {
  995. response = cache[current.searchTerm]
  996. } else {
  997. response = await asyncRequest({
  998. method: 'POST',
  999. url: baseURLautosearch,
  1000. data: 'search_term=' + encodeURIComponent(current.searchTerm) + '&image_size=98&search_each=1&sort_type=popular',
  1001. headers: {
  1002. Referer: current.metaurl,
  1003. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  1004. // Host: 'www.metacritic.com',
  1005. 'User-Agent': 'MetacriticUserscript Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0',
  1006. 'X-Requested-With': 'XMLHttpRequest'
  1007. }
  1008. })
  1009. response = {
  1010. time: (new Date()).toJSON(),
  1011. json: JSON.parse(response.responseText)
  1012. }
  1013. cache[current.searchTerm] = response
  1014. await GM.setValue('autosearchcache', JSON.stringify(cache))
  1015. }
  1016.  
  1017. if (!response || !('json' in response)) {
  1018. alert('ShowMetacriticRatings: Error 05')
  1019. }
  1020. const data = response.json
  1021. let multiple = false
  1022. if (data && data.autoComplete && data.autoComplete.results && data.autoComplete.results.length) {
  1023. // Remove data with wrong type
  1024. data.autoComplete = data.autoComplete.results
  1025.  
  1026. const newdata = []
  1027. data.autoComplete.forEach(function (result) {
  1028. if (metacritic2searchType(result.refType) === current.type) {
  1029. newdata.push(result)
  1030. }
  1031. })
  1032. data.autoComplete = newdata
  1033. if (data.autoComplete.length === 0) {
  1034. // No results
  1035. console.debug('ShowMetacriticRatings: No results (after filtering by type) for searchTerm=' + current.searchTerm)
  1036. } else if (data.autoComplete.length === 1) {
  1037. // One result, let's show it
  1038. if (!await isBlacklistedUrl(document.location.href, absoluteMetaURL(data.autoComplete[0].url))) {
  1039. current.metaurl = absoluteMetaURL(data.autoComplete[0].url)
  1040. loadMetacriticUrl(true)
  1041. return
  1042. }
  1043. } else {
  1044. // More than one result
  1045. multiple = true
  1046. console.debug('ShowMetacriticRatings: Multiple results for searchTerm=' + current.searchTerm)
  1047. const exactMatches = []
  1048. data.autoComplete.forEach(function (result, i) { // Try to find the correct result by matching the search term to exactly one movie title
  1049. if (current.searchTerm === result.name) {
  1050. exactMatches.push(result)
  1051. }
  1052. })
  1053. if (exactMatches.length === 1) {
  1054. // Only one exact match, let's show it
  1055. console.debug('ShowMetacriticRatings: Only one exact match for searchTerm=' + current.searchTerm)
  1056. if (!await isBlacklistedUrl(document.location.href, absoluteMetaURL(exactMatches[0].url))) {
  1057. current.metaurl = absoluteMetaURL(exactMatches[0].url)
  1058. loadMetacriticUrl(true)
  1059. return
  1060. }
  1061. }
  1062. }
  1063. } else {
  1064. console.debug('ShowMetacriticRatings: No results (at all) for searchTerm=' + current.searchTerm)
  1065. }
  1066. // HERE: multiple results or no result. The user may type "meta" now
  1067. if (multiple) {
  1068. balloonAlert('Multiple metacritic results. Type &#34;meta&#34; for manual search.', 10000, false, { bottom: 5, top: 'auto', maxWidth: 400, paddingRight: 5 }, () => openSearchBox(true))
  1069. }
  1070. }
  1071.  
  1072. function openSearchBox (search) {
  1073. let query
  1074. if (current.type === 'music') {
  1075. query = current.data[0]
  1076. } else {
  1077. query = current.data.join(' ')
  1078. }
  1079. $('#mcdiv123').remove()
  1080. const div = $('<div id="mcdiv123"></div>').appendTo(document.body)
  1081. div.css({
  1082. position: 'fixed',
  1083. bottom: 0,
  1084. left: 0,
  1085. minWidth: 300,
  1086. maxHeight: '80%',
  1087. maxWidth: 640,
  1088. overflow: 'auto',
  1089. backgroundColor: '#fff',
  1090. border: '2px solid #bbb',
  1091. borderRadius: ' 6px',
  1092. boxShadow: '0 0 3px 3px rgba(100, 100, 100, 0.2)',
  1093. color: '#000',
  1094. padding: ' 3px',
  1095. zIndex: '2147483601'
  1096. })
  1097.  
  1098. GM.getValue('position', false).then(function (s) {
  1099. if (s) {
  1100. div.css({
  1101. top: '',
  1102. left: '',
  1103. bottom: '',
  1104. right: ''
  1105. })
  1106. div.css(JSON.parse(s))
  1107. }
  1108. })
  1109.  
  1110. $('<input type="text" size="60" id="mcisearchquery" style="background:white;color:black;">').appendTo(div).focus().val(query).on('keypress', function (e) {
  1111. const code = e.keyCode || e.which
  1112. if (code === 13) { // Enter key
  1113. searchBoxSearch(e, $('#mcisearchquery').val())
  1114. }
  1115. })
  1116. $('<button id="mcisearchbutton" style="background:silver;color:black;">').text('Search').appendTo(div).click((ev) => searchBoxSearch(ev, $('#mcisearchquery').val()))
  1117. }
  1118. async function searchBoxSearch (ev, query) {
  1119. if (!query) { // Use values from search form
  1120. query = current.searchTerm
  1121. }
  1122.  
  1123. const type = searchType2metacritic(current.type)
  1124.  
  1125. const style = document.createElement('style')
  1126. style.type = 'text/css'
  1127. style.innerHTML = CSS
  1128. document.head.appendChild(style)
  1129.  
  1130. const div = $('#mcdiv123')
  1131. const loader = $('<div style="width:20px; height:20px;display:inline-block" class="grespinner"></div>').appendTo($('#mcisearchbutton'))
  1132.  
  1133. const url = baseURLsearch.replace('{type}', encodeURIComponent(type)).replace('{query}', encodeURIComponent(query))
  1134.  
  1135. const response = await asyncRequest({
  1136. url,
  1137. data: 'search_term=' + encodeURIComponent(current.searchTerm) + '&image_size=98&search_each=1&sort_type=popular',
  1138. headers: {
  1139. Referer: url,
  1140. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  1141. // Host: 'www.metacritic.com',
  1142. 'User-Agent': 'MetacriticUserscript ' + navigator.userAgent
  1143. }
  1144. }).catch(function (response) {
  1145. alert('Search failed!\n' + response.finalUrl + '\nStatus: ' + response.status + '\n' + response.responseText ? response.responseText.substring(0, 500) : 'Empty response')
  1146. })
  1147.  
  1148. const results = []
  1149. if (!~response.responseText.indexOf('No search results found.')) {
  1150. const d = $('<html>').html(response.responseText)
  1151. d.find('ul.search_results.module .result').each(function () {
  1152. results.push(this.innerHTML)
  1153. })
  1154. }
  1155.  
  1156. if (results && results.length > 0) {
  1157. // Show results
  1158. loader.remove()
  1159.  
  1160. const accept = function (ev) {
  1161. const parentDiv = $(this.parentNode)
  1162. const a = parentDiv.find("a[href*='metacritic.com']")
  1163. const metaurl = a.attr('href')
  1164. const docurl = document.location.href
  1165.  
  1166. const resultDivParent = parentDiv.parent()
  1167. resultDivParent.html('')
  1168. resultDivParent.append(loader)
  1169.  
  1170. removeFromBlacklist(docurl, metaurl).then(function () {
  1171. addToMap(docurl, metaurl).then(function () {
  1172. current.metaurl = metaurl
  1173. loadMetacriticUrl().then(() => loader.remove())
  1174. })
  1175. })
  1176. }
  1177. const denyAll = function (ev) {
  1178. const docurl = document.location.href
  1179. $('#mcdiv123searchresults').find("div.result a[href*='metacritic.com']").each(function () {
  1180. addToBlacklist(docurl, this.href)
  1181. })
  1182. }
  1183.  
  1184. const resultdiv = $('#mcdiv123searchresults').length ? $('#mcdiv123searchresults').html('') : $('<div id="mcdiv123searchresults"></div>').css('max-width', '95%').appendTo(div)
  1185. results.forEach(function (html) {
  1186. const singleresult = $('<div class="result"></div>').html(fixMetacriticURLs(html) + '<div style="clear:left"></div>').appendTo(resultdiv)
  1187. $('<span title="Assist us: This is the correct entry!" style="cursor:pointer; color:green; font-size: 13px;">&check;</span>').prependTo(singleresult).click(accept)
  1188. })
  1189. resultdiv.find('.metascore_w.album').removeClass('album') // Remove some classes
  1190. resultdiv.find('.must-see').remove() // Remove some elements
  1191.  
  1192. const sub = $('#mcdiv123 .sub').length ? $('#mcdiv123 .sub').html('') : $('<div class="sub"></div>').appendTo(div)
  1193. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + url + '" title="Open Metacritic">' + decodeURI(url.replace('https://www.', '@')) + '</a>').appendTo(sub)
  1194. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px;">&#10062;</span>').appendTo(sub).click(function () {
  1195. document.body.removeChild(this.parentNode.parentNode)
  1196. })
  1197. $('<span title="Assist us: None of the above is the correct item!" style="cursor:pointer; float:right; color:crimson; font-size: 11px;">&cross;</span>').appendTo(sub).click(function () { if (confirm('None of the above is the correct item\nConfirm?')) denyAll() })
  1198. } else {
  1199. // No results
  1200. loader.remove()
  1201. const resultdiv = $('#mcdiv123searchresults').length ? $('#mcdiv123searchresults').html('') : $('<div id="mcdiv123searchresults"></div>').appendTo(div)
  1202. resultdiv.html('No search results.')
  1203.  
  1204. const sub = $('#mcdiv123 .sub').length ? $('#mcdiv123 .sub').html('') : $('<div class="sub"></div>').appendTo(div)
  1205. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + url + '" title="Open Metacritic">' + decodeURI(url.replace('https://www.', '@')) + '</a>').appendTo(sub)
  1206. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px;">&#10062;</span>').appendTo(sub).click(function () {
  1207. document.body.removeChild(this.parentNode.parentNode)
  1208. })
  1209. }
  1210. }
  1211.  
  1212. function showHoverInfo (response, orgMetaUrl) {
  1213. const html = fixMetacriticURLs(response.responseText)
  1214. const time = new Date(response.time)
  1215. const url = response.finalUrl
  1216.  
  1217. $('#mcdiv123').remove()
  1218. const div = $('<div id="mcdiv123"></div>').appendTo(document.body)
  1219. div.css({
  1220. position: 'fixed',
  1221. bottom: 0,
  1222. left: 0,
  1223. minWidth: 150,
  1224. backgroundColor: '#fff',
  1225. border: '2px solid #bbb',
  1226. borderRadius: ' 6px',
  1227. boxShadow: '0 0 3px 3px rgba(100, 100, 100, 0.2)',
  1228. color: '#000',
  1229. padding: ' 3px',
  1230. zIndex: '2147483601'
  1231. })
  1232.  
  1233. GM.getValue('position', false).then(function (s) {
  1234. if (s) {
  1235. div.css({
  1236. top: '',
  1237. left: '',
  1238. bottom: '',
  1239. right: ''
  1240. })
  1241. div.css(JSON.parse(s))
  1242. }
  1243. })
  1244.  
  1245. // Functions for communication between page and iframe
  1246. // Mozilla can access parent.document
  1247. // Chrome can use postMessage()
  1248. let frameStatus = false // if this remains false, loading the frame content failed. A reason could be "Content Security Policy"
  1249. function loadExternalImage (url, myframe) {
  1250. // Load external image, bypass CSP
  1251. GM.xmlHttpRequest({
  1252. method: 'GET',
  1253. url,
  1254. responseType: 'arraybuffer',
  1255. onload: function (response) {
  1256. myframe.contentWindow.postMessage({
  1257. mcimessage_imgLoaded: true,
  1258. mcimessage_imgData: response.response,
  1259. mcimessage_imgOrgSrc: url
  1260. }, '*')
  1261. }
  1262. })
  1263. }
  1264. const functions = {
  1265. parent: function () {
  1266. const f = parent.document.getElementById('mciframe123')
  1267. let lastdiff = -200000
  1268. window.addEventListener('message', function (e) {
  1269. if (typeof e.data !== 'object') {
  1270. return
  1271. } else if ('mcimessage0' in e.data) {
  1272. frameStatus = true // Frame content was loaded successfully
  1273. } else if ('mcimessage1' in e.data) {
  1274. f.style.width = parseInt(f.style.width) + 5 + 'px'
  1275. if (e.data.heightdiff === lastdiff) {
  1276. f.style.height = parseInt(f.style.height) + 10 + 'px'
  1277. }
  1278. lastdiff = e.data.heightdiff
  1279. } else if ('mcimessage2' in e.data) {
  1280. f.style.height = parseInt(f.style.height) + 10 + 'px'
  1281. } else if ('mcimessage_loadImg' in e.data) {
  1282. loadExternalImage(e.data.mcimessage_imgUrl, f)
  1283. } else {
  1284. return
  1285. }
  1286. if (f.contentWindow != null) {
  1287. f.contentWindow.postMessage({
  1288. mcimessage3: true,
  1289. mciframe123_clientHeight: f.clientHeight,
  1290. mciframe123_clientWidth: f.clientWidth
  1291. }, '*')
  1292. }
  1293. })
  1294. },
  1295. frame: function () {
  1296. parent.postMessage({ mcimessage0: true }, '*') // Loading frame content was successfull
  1297.  
  1298. let i = 0
  1299. window.addEventListener('message', function (e) {
  1300. if (typeof e.data === 'object' && 'mcimessage_imgLoaded' in e.data) {
  1301. // Load external image
  1302. const arrayBufferView = new Uint8Array(e.data.mcimessage_imgData)
  1303. const blob = new Blob([arrayBufferView], { type: 'image/jpeg' })
  1304. const urlCreator = window.URL || window.webkitURL
  1305. const imageUrl = urlCreator.createObjectURL(blob)
  1306. const img = failedImages[e.data.mcimessage_imgOrgSrc]
  1307. img.src = imageUrl
  1308. }
  1309.  
  1310. if (!('mcimessage3' in e.data)) return
  1311.  
  1312. if (e.data.mciframe123_clientHeight < document.body.scrollHeight && i < 100) {
  1313. parent.postMessage({ mcimessage2: 1 }, '*')
  1314. i++
  1315. }
  1316. if (i >= 100) {
  1317. parent.postMessage({ mcimessage1: 1, heightdiff: document.body.scrollHeight - e.data.mciframe123_clientHeight }, '*')
  1318. i = 0
  1319. }
  1320. })
  1321. parent.postMessage({ mcimessage1: 1, heightdiff: -100000 }, '*')
  1322. }
  1323.  
  1324. }
  1325.  
  1326. const css = `
  1327. #hover_div_a20230915{font-family:sans-serif;color:#262626;font-size:1rem;line-height:1.625rem}#hover_div_a20230915 a,#hover_div_a20230915 a:hover{text-decoration:none}#hover_div_a20230915 a:hover{color:#09f}#hover_div_a20230915 a{color:#000}#hover_div_a20230915 a:focus{color:grey}#hover_div_a20230915 .g-border-black,#hover_div_a20230915 .g-border-gray100{border-color:#000}#hover_div_a20230915 .g-color-black,#hover_div_a20230915 .g-color-gray100{color:#000}#hover_div_a20230915 .g-border-gray98{border-color:#191919}#hover_div_a20230915 .g-color-gray98{color:#191919}#hover_div_a20230915 .g-border-gray90{border-color:#262626}#hover_div_a20230915 .g-color-gray90{color:#262626}#hover_div_a20230915 .g-border-gray80{border-color:#404040}#hover_div_a20230915 .g-color-gray80{color:#404040}#hover_div_a20230915 .g-border-gray70{border-color:#666}#hover_div_a20230915 .g-color-gray70{color:#666}#hover_div_a20230915 .g-border-gray60{border-color:grey}#hover_div_a20230915 .g-color-gray60{color:grey}#hover_div_a20230915 .g-border-gray50{border-color:#999}#hover_div_a20230915 .g-color-gray50{color:#999}#hover_div_a20230915 .g-border-gray40{border-color:#bfbfbf}#hover_div_a20230915 .g-color-gray40{color:#bfbfbf}#hover_div_a20230915 .g-border-gray30{border-color:#d8d8d8}#hover_div_a20230915 .g-color-gray30{color:#d8d8d8}#hover_div_a20230915 .g-border-gray20{border-color:#e6e6e6}#hover_div_a20230915 .g-color-gray20{color:#e6e6e6}#hover_div_a20230915 .g-border-gray10{border-color:#f2f2f2}#hover_div_a20230915 .g-color-gray10{color:#f2f2f2}#hover_div_a20230915 .g-border-gray0,#hover_div_a20230915 .g-border-white{border-color:#fff}#hover_div_a20230915 .g-color-gray0,#hover_div_a20230915 .g-color-white{color:#fff}#hover_div_a20230915 .g-border-red{border-color:#eb0036}#hover_div_a20230915 .g-color-red{color:#eb0036}#hover_div_a20230915 .g-border-green{border-color:#01b44f}#hover_div_a20230915 .g-color-green{color:#01b44f}#hover_div_a20230915 .g-width-large{width:1.5rem}#hover_div_a20230915 .g-height-large{height:1.5rem}#hover_div_a20230915 .g-width-100{width:100%}#hover_div_a20230915 .g-height-100{height:100%}#hover_div_a20230915 .g-text-large{font-size:1.5rem;line-height:2rem}#hover_div_a20230915 .g-text-xxsmall{font-size:xx-small}#hover_div_a20230915 .g-text-bold{font-weight:700}#hover_div_a20230915 .g-text-link{text-decoration:underline}#hover_div_a20230915 .u-block{display:block}#hover_div_a20230915 .u-flexbox{display:flex}#hover_div_a20230915 .u-flexbox-column{display:flex;flex-direction:column}#hover_div_a20230915 .u-flexbox-justifyCenter{justify-content:center}#hover_div_a20230915 .u-flexbox-alignCenter{align-items:center}#hover_div_a20230915 .u-grid{display:grid;grid-gap:0;grid-gap:var(--grid-gap,0)}#hover_div_a20230915 .u-grid-2column{-ms-grid-columns:50% 50%;display:grid;grid-template:auto/repeat(2,1fr)}#hover_div_a20230915 .u-grid-3column{-ms-grid-columns:33.3% 33.3% 33.3%;display:grid;grid-template:auto/repeat(3,1fr)}#hover_div_a20230915 .u-grid-4column{-ms-grid-columns:25% 25% 25% 25%;display:grid;grid-template:auto/repeat(4,1fr)}#hover_div_a20230915 .u-grid-5column{-ms-grid-columns:20% 20% 20% 20% 20%;display:grid;grid-template:auto/repeat(5,1fr)}#hover_div_a20230915 .u-grid-7column{-ms-grid-columns:14.2857% 14.2857% 14.2857% 14.2857% 14.2857% 14.2857% 14.2857%;display:grid;grid-template:auto/repeat(7,1fr)}#hover_div_a20230915 .u-grid-column-span2{grid-column-end:span 2}#hover_div_a20230915 .u-grid-column-span3{grid-column-end:span 3}#hover_div_a20230915 .u-grid-column-span4{grid-column-end:span 4}#hover_div_a20230915 .u-text-center{text-align:center}#hover_div_a20230915 .c-siteReviewScore_large{border-radius:0.5rem;height:4rem;width:4rem;font-size:2rem}#hover_div_a20230915 .c-siteReviewScore_user{border-radius:50%}#hover_div_a20230915 .c-reviewsStats{padding:1rem 0;grid-template-columns:1fr 1fr 1fr;justify-content:space-evenly;font-size:0.75rem;line-height:1.25rem}#hover_div_a20230915 div[class^=c-reviewsStats_]:first-child,#hover_div_a20230915 div[class^=c-reviewsStats_]:nth-child(2){border-right:0.0625rem solid #d8d8d8}#hover_div_a20230915 .c-ScoreCardGraph{overflow:hidden;white-space:nowrap}#hover_div_a20230915 .c-ScoreCardGraph > div{margin-left:0.25rem;padding:0 0.25rem;text-align:right;height:0.5rem;min-width:2rem;line-height:1rem}#hover_div_a20230915 .c-ScoreCardGraph > div:first-child{margin-left:0}#hover_div_a20230915 .c-ScoreCardGraph_scoreTitle{letter-spacing:0.25rem}#hover_div_a20230915 .c-ScoreCardGraph_scoreSentiment{color:#00ce7a}#hover_div_a20230915 .c-ScoreCardGraph_scoreGraphPositive{background:#00ce7a;border-radius:0.25rem 0 0 0.25rem}#hover_div_a20230915 .c-ScoreCardGraph_scoreGraphNeutral{background:#ffbd3f}#hover_div_a20230915 .c-ScoreCardGraph_scoreGraphNegative{background:#ff6874;border-radius:0 0.25rem 0.25rem 0}#hover_div_a20230915 .gray{background:#bfbfbf;height:1rem;display:inline-block}#hover_div_a20230915 .c-ScoreCard_scoreContent{display:flex;align-content:flex-start;flex-wrap:nowrap;grid-gap:10px;gap:10px;width:100%;justify-content:space-between;align-items:stretch}#hover_div_a20230915 .c-ScoreCard_scoreContent_text{line-height:normal;display:flex;flex-direction:column;justify-content:space-between}#hover_div_a20230915 .c-ScoreCard_scoreContent_number > .c-siteReviewScore_background-critic_large,#hover_div_a20230915 .c-ScoreCard_scoreContent_number > .c-siteReviewScore_background-critic_large .c-siteReviewScore_large{width:4rem;height:4rem}#hover_div_a20230915 .c-ScoreCard_scoreSentiment{font-size:1rem;line-height:1.25rem;text-transform:capitalize}#hover_div_a20230915 .c-ScoreCard_scoreTitle{letter-spacing:0.25rem}#hover_div_a20230915 .c-reviewsOverview_overviewDetails{grid-template-columns:1fr 1fr;grid-gap:1.25rem;border-top:1px solid #262626;margin-top:auto;padding:2px}#hover_div_a20230915 .c-reviewsOverview_overviewDetails:first-child{border-top:0 solid #262626}#hover_div_a20230915 .c-siteReviewScore_green{background:#00ce7a}#hover_div_a20230915 .c-siteReviewScore_yellow{background:#ffbd3f}#hover_div_a20230915 .c-siteReviewScore_red{background:#ff6874}#hover_div_a20230915 .c-siteReviewScore_grey{background:#404040}#hover_div_a20230915 .c-siteReviewScore_tbdCritic,#hover_div_a20230915 .c-siteReviewScore_tbdUser{border-width:0.125rem;border-style:solid}#hover_div_a20230915 .o-inlineScore{border-radius:0.25rem;font-size:1.25rem;font-weight:700;color:#404040;width:2.5rem;height:2.5rem;display:inline-flex;justify-content:center;align-items:center;text-decoration:none!important}#hover_div_a20230915 .o-inlineScore-green{background:#00ce7a}#hover_div_a20230915 .o-inlineScore-yellow{background:#ffbd3f}#hover_div_a20230915 .o-inlineScore-red{background:#ff6874}#hover_div_a20230915 .o-inlineScore-tbd{border:1px solid grey}#hover_div_a20230915 .u-pointer{cursor:pointer}#hover_div_a20230915 .c-siteReviewScore_green{background:#00ce7a}#hover_div_a20230915 .c-siteReviewScore_yellow{background:#ffbd3f}#hover_div_a20230915 .c-siteReviewScore_red{background:#ff6874}#hover_div_a20230915 .c-siteReviewScore_grey{background:#404040}#hover_div_a20230915 .c-siteReviewScore_tbdCritic,#hover_div_a20230915 .c-siteReviewScore_tbdUser{border-width:0.125rem;border-style:solid}#hover_div_a20230915{max-width:440px}
  1328. `
  1329.  
  1330. let framesrc = 'data:text/html,'
  1331. framesrc += encodeURIComponent(`<!DOCTYPE html>
  1332. <html lang="en">
  1333. <head>
  1334. <meta charset="utf-8">
  1335. <title>Metacritic info</title>
  1336. <style>body { margin:0px; padding:0px; background:white; }${css}
  1337. </style>
  1338. <script>
  1339. const failedImages = {};
  1340. function detectCSP(img) {
  1341. if(img.complete && (!img.naturalWidth || !img.naturalHeight)) {
  1342. return true;
  1343. }
  1344. return false;
  1345. }
  1346. function findCSPerrors() {
  1347. const imgs = document.querySelectorAll("img");
  1348. for(let i = 0; i < imgs.length; i++) {
  1349. if(imgs[i].complete && detectCSP(imgs[i])) {
  1350. fixCSP(imgs[i]);
  1351. }
  1352. }
  1353. }
  1354. function fixCSP(img) {
  1355. console.debug("ShowMetacriticRatings(iFrame): Loading image failed. Bypassing CSP...");
  1356. failedImages[img.src] = img;
  1357. parent.postMessage({"mcimessage_loadImg":true, "mcimessage_imgUrl": img.src},"*");
  1358. }
  1359. function on_load() {
  1360. (${functions.frame.toString()})();
  1361. window.setTimeout(findCSPerrors, 500);
  1362. }
  1363. </script>
  1364. </head>
  1365. <body onload="on_load();">
  1366. <div style="border:0px solid; display:block; position:relative; border-radius:0px; padding:0px; margin:0px; box-shadow:none;" class="hover_div" id="hover_div">
  1367. <div class="hover_content">${html}</div>
  1368. </div>
  1369. </body>
  1370. </html>`)
  1371.  
  1372. const frame = $('<iframe></iframe>').appendTo(div)
  1373. frame.attr('id', 'mciframe123')
  1374. frame.attr('src', framesrc)
  1375. frame.attr('scrolling', 'auto')
  1376. frame.css({
  1377. width: 440,
  1378. height: 110,
  1379. border: 'none'
  1380. })
  1381.  
  1382. window.setTimeout(function () {
  1383. if (!frameStatus) { // Loading frame content failed.
  1384. // Directly inject the html without an iframe (this may break the site or the metacritic)
  1385. console.debug('ShowMetacriticRatings: Loading iframe content failed. Injecting directly.')
  1386. $('head').append(`<style>${css}</style>`)
  1387. const noframe = $(`<div style="border:0px solid; display:block; position:relative; border-radius:0px; padding:0px; margin:0px; box-shadow:none;" class="hover_div" id="hover_div">
  1388. <div class="hover_content">${html}</div>
  1389. </div>`)
  1390. frame.replaceWith(noframe)
  1391. }
  1392. }, 2000)
  1393.  
  1394. functions.parent()
  1395.  
  1396. const sub = $('<div></div>').appendTo(div)
  1397. $('<time style="color:#b6b6b6; font-size: 11px;" datetime="' + time + '" title="' + time.toLocaleTimeString() + ' ' + time.toLocaleDateString() + '">' + minutesSince(time) + '</time>').appendTo(sub)
  1398. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + url + '" title="Open Metacritic">' + decodeURI(url.replace('https://www.', '@')) + '</a>').appendTo(sub)
  1399. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px; padding-left:5px;">&#10062;</span>').data('url', current.metaurl).appendTo(sub).click(function () {
  1400. const metaurl = $(this).data('url')
  1401. addToTemporaryBlacklist(metaurl)
  1402. document.body.removeChild(this.parentNode.parentNode)
  1403. })
  1404.  
  1405. $('<span title="Assist us: This is the correct entry!" style="cursor:pointer; float:right; color:green; font-size: 11px;">&check;</span>').data('url', current.metaurl).appendTo(sub).click(function () {
  1406. const docurl = document.location.href
  1407. const metaurl = $(this).data('url')
  1408. addToMap(docurl, metaurl).then(function (r) {
  1409. balloonAlert('Thanks for your submission!\n\nSaved as a correct entry.\n\n' + r[0] + '\n' + r[1], 6000, 'Success')
  1410. })
  1411. })
  1412. $('<span title="Assist us: This is NOT the correct entry!" style="cursor:pointer; float:right; color:crimson; font-size: 11px;">&cross;</span>').data('url', current.metaurl).appendTo(sub).click(function () {
  1413. if (!confirm('This is NOT the correct entry!\n\nAdd to blacklist?')) return
  1414. const docurl = document.location.href
  1415. const metaurl = $(this).data('url')
  1416. addToBlacklist(docurl, metaurl).then(function (r) {
  1417. balloonAlert('Thanks for your submission!\n\nSaved to blacklist.\n\n' + r[0] + '\n' + r[1], 6000, 'Success')
  1418. })
  1419.  
  1420. openSearchBox(true)
  1421. })
  1422.  
  1423. // Store response in cache:
  1424. if (!('cached' in response)) {
  1425. storeInHoverCache(current.metaurl, response, orgMetaUrl)
  1426. }
  1427. }
  1428.  
  1429. function metacriticGeneralProductSetup () {
  1430. current.broadenCounter = 0
  1431. }
  1432.  
  1433. const metacritic = {
  1434. mapped: function metacriticMapped (docurl, product, metaurl, type, searchTerm) {
  1435. // url was in the map/whitelist
  1436. current.data = searchTerm ? [searchTerm] : []
  1437. current.docurl = docurl
  1438. current.product = product
  1439. current.metaurl = metaurl
  1440. current.type = type
  1441. current.searchTerm = searchTerm || null
  1442. loadMetacriticUrl()
  1443. },
  1444. music: function metacriticMusic (docurl, product, artistname, albumname) {
  1445. current.data = [albumname.trim(), artistname.trim()]
  1446. artistname = name2metacritic(artistname)
  1447. albumname = albumname.replace('&', ' ')
  1448. albumname = name2metacritic(albumname)
  1449. current.docurl = docurl
  1450. current.product = product
  1451. current.metaurl = baseURLmusic + albumname + '/' + artistname
  1452. current.type = 'music'
  1453. current.searchTerm = albumname + '/' + artistname
  1454. loadMetacriticUrl()
  1455. },
  1456. movie: function metacriticMovie (docurl, product, moviename) {
  1457. current.data = [moviename.trim()]
  1458. moviename = name2metacritic(moviename)
  1459. current.docurl = docurl
  1460. current.product = product
  1461. current.metaurl = baseURLmovie + moviename
  1462. current.type = 'movie'
  1463. current.searchTerm = moviename
  1464. loadMetacriticUrl()
  1465. },
  1466. tv: function metacriticTv (docurl, product, seriesname) {
  1467. current.data = [seriesname.trim()]
  1468. seriesname = name2metacritic(seriesname)
  1469. current.docurl = docurl
  1470. current.product = product
  1471. current.metaurl = baseURLtv + seriesname
  1472. current.type = 'tv'
  1473. current.searchTerm = seriesname
  1474. loadMetacriticUrl()
  1475. },
  1476. pcgame: function metacriticPcgame (docurl, product, gamename) {
  1477. current.data = [gamename.trim()]
  1478. gamename = name2metacritic(gamename)
  1479. current.docurl = docurl
  1480. current.product = product
  1481. current.metaurl = baseURLpcgame + gamename
  1482. current.type = 'pcgame'
  1483. current.searchTerm = gamename
  1484. loadMetacriticUrl()
  1485. },
  1486. ps4game: function metacriticPs4game (docurl, product, gamename) {
  1487. current.data = [gamename.trim()]
  1488. gamename = name2metacritic(gamename)
  1489. current.docurl = docurl
  1490. current.product = product
  1491. current.metaurl = baseURLps4 + gamename
  1492. current.type = 'ps4game'
  1493. current.searchTerm = gamename
  1494. loadMetacriticUrl()
  1495. },
  1496. xonegame: function metacriticXonegame (docurl, product, gamename) {
  1497. current.data = [gamename.trim()]
  1498. gamename = name2metacritic(gamename)
  1499. current.docurl = docurl
  1500. current.product = product
  1501. current.metaurl = baseURLxone + gamename
  1502. current.type = 'xonegame'
  1503. current.searchTerm = gamename
  1504. loadMetacriticUrl()
  1505. }
  1506. }
  1507.  
  1508. const Always = () => true
  1509. const sites = {
  1510. bandcamp: {
  1511. host: ['bandcamp.com'],
  1512. condition: () => unsafeWindow && unsafeWindow.TralbumData && unsafeWindow.TralbumData.current,
  1513. products: [{
  1514. condition: Always,
  1515. type: 'music',
  1516. data: () => [unsafeWindow.TralbumData.artist, unsafeWindow.TralbumData.current.title]
  1517. }]
  1518. },
  1519. itunes: {
  1520. host: ['itunes.apple.com'],
  1521. condition: Always,
  1522. products: [{
  1523. condition: () => ~document.location.href.indexOf('/movie/'),
  1524. type: 'movie',
  1525. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  1526. },
  1527. {
  1528. condition: () => ~document.location.href.indexOf('/tv-season/'),
  1529. type: 'tv',
  1530. data: function () {
  1531. let name = parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  1532. if (~name.indexOf(', Season')) {
  1533. name = name.split(', Season')[0]
  1534. }
  1535. return name
  1536. }
  1537. },
  1538. {
  1539. condition: () => ~document.location.href.indexOf('/album/'),
  1540. type: 'music',
  1541. data: function () {
  1542. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  1543. const album = ld[0]
  1544. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  1545. return [artist, album]
  1546. }
  1547. }]
  1548. },
  1549. 'music.apple': {
  1550. host: ['music.apple.com'],
  1551. condition: Always,
  1552. products: [{
  1553. condition: () => ~document.location.href.indexOf('/album/') && parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum')).length > 1,
  1554. type: 'music',
  1555. data: function () {
  1556. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  1557. const album = ld[0]
  1558. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  1559. return [artist, album]
  1560. }
  1561. }]
  1562. },
  1563. googleplay: {
  1564. host: ['play.google.com'],
  1565. condition: Always,
  1566. products: [
  1567. {
  1568. condition: () => ~document.location.href.indexOf('/album/'),
  1569. type: 'music',
  1570. data: () => [document.querySelector('[itemprop="byArtist"] meta[itemprop="name"]').content, document.querySelector('[itemtype="https://schema.org/MusicAlbum"] meta[itemprop="name"]').content]
  1571. },
  1572. {
  1573. condition: () => ~document.location.href.indexOf('/movies/details/'),
  1574. type: 'movie',
  1575. data: () => document.querySelector('*[itemprop=name]').textContent
  1576. }
  1577. ]
  1578. },
  1579. imdb: {
  1580. host: ['imdb.com'],
  1581. condition: () => !~document.location.pathname.indexOf('/mediaviewer') && !~document.location.pathname.indexOf('/mediaindex') && !~document.location.pathname.indexOf('/videoplayer'),
  1582. products: [
  1583. {
  1584. condition: () => document.querySelector('a[href*="/criticreviews/"'),
  1585. type: 'mapped',
  1586. data: async function () {
  1587. // This is used if there is a metacritic link on the imdb page
  1588. const criticsUrl = document.querySelector('a[href*="/criticreviews/"').href.toString()
  1589. const response = await asyncRequest({ url: criticsUrl }).catch(function (response) {
  1590. console.warn('ShowMetacriticRatings: Error imdb01\nurl=' + criticsUrl + '\nstatus=' + response.status)
  1591. })
  1592. const m = response.responseText.match(/(https:\/\/www\.metacritic\.com\/(\w+)\/[^?&"']+)/)
  1593. console.debug('ShowMetacriticRatings: Metacritic link found on imdb:', m[2], m[1])
  1594. const query = document.querySelector('[data-testid="hero__pageTitle"]') ? document.querySelector('[data-testid="hero__pageTitle"]').textContent : null
  1595. return [m[1], m[2], query]
  1596. }
  1597. },
  1598. {
  1599. condition: function () {
  1600. const e = document.querySelector("meta[property='og:type']")
  1601. if (e && e.content === 'video.movie') {
  1602. return true
  1603. } else if (document.querySelector('[data-testid="hero__pageTitle"]') && !document.querySelector('[data-testid="hero-subnav-bar-left-block"] a[href*="episodes/"]')) {
  1604. return true
  1605. }
  1606. return false
  1607. },
  1608. type: 'movie',
  1609. data: async function () {
  1610. // If the page is not in English or the browser is not in English, request page in English.
  1611. // Then the title in <h1> will be the English title and Metacritic always uses the English title.
  1612. if (document.querySelector('[for="nav-language-selector"]').textContent.toLowerCase() !== 'en' || !navigator.language.startsWith('en')) {
  1613. // Set language cookie to English, request current page in English, then restore language cookie or expire it if it didn't exist before
  1614. const langM = document.cookie.match(/lc-main=([^;]+)/)
  1615. const langBefore = langM ? langM[0] : ';expires=Thu, 01 Jan 1970 00:00:01 GMT'
  1616. document.cookie = 'lc-main=en-US'
  1617. const response = await asyncRequest({
  1618. url: document.location.href,
  1619. headers: {
  1620. 'Accept-Language': 'en-US,en'
  1621. }
  1622. }).catch(function (response) {
  1623. console.warn('ShowMetacriticRatings: Error imdb02\nurl=' + document.location.href + '\nstatus=' + response.status)
  1624. })
  1625. document.cookie = 'lc-main=' + langBefore
  1626. // Extract <h1> title
  1627. const parts = response.responseText.split('</span></h1>')[0].split('>')
  1628. console.debug('ShowMetacriticRatings: Movie title from English page:', parts[parts.length - 1])
  1629. return parts[parts.length - 1]
  1630. } else if (document.querySelector('script[type="application/ld+json"]')) {
  1631. const ld = parseLDJSON(['name', 'alternateName'])
  1632. if (ld.length > 1 && ld[1]) {
  1633. console.debug('ShowMetacriticRatings: Movie ld+json alternateName', ld[1])
  1634. return ld[1]
  1635. }
  1636. console.debug('ShowMetacriticRatings: Movie ld+json name', ld[0])
  1637. return ld[0]
  1638. } else {
  1639. console.debug('ShowMetacriticRatings: Movie <title>', document.title.match(/(.+?)\s+(\(\d+\))? - IMDb/)[1])
  1640. return document.title.match(/(.+?)\s+(\(\d+\))? - IMDb/)[1]
  1641. }
  1642. }
  1643. },
  1644. {
  1645. condition: function () {
  1646. const e = document.querySelector("meta[property='og:type']")
  1647. if (e && e.content === 'video.tv_show') {
  1648. return true
  1649. } else if (document.querySelector('[data-testid="hero-subnav-bar-left-block"] a[href*="episodes/"]')) {
  1650. return true
  1651. }
  1652. return false
  1653. },
  1654. type: 'tv',
  1655. data: async function () {
  1656. if (document.querySelector('[for="nav-language-selector"]').textContent.toLowerCase() !== 'en' || !navigator.language.startsWith('en')) {
  1657. // Set language cookie to English, request current page in English, then restore language cookie or expire it if it didn't exist before
  1658. const langM = document.cookie.match(/lc-main=([^;]+)/)
  1659. const langBefore = langM ? langM[0] : ';expires=Thu, 01 Jan 1970 00:00:01 GMT'
  1660. document.cookie = 'lc-main=en-US'
  1661. const response = await asyncRequest({
  1662. url: document.location.href,
  1663. headers: {
  1664. 'Accept-Language': 'en-US,en'
  1665. }
  1666. }).catch(function (response) {
  1667. console.warn('ShowMetacriticRatings: Error imdb03\nurl=' + document.location.href + '\nstatus=' + response.status)
  1668. })
  1669. document.cookie = 'lc-main=' + langBefore
  1670. // Extract <h1> title
  1671. const parts = response.responseText.split('</span></h1>')[0].split('>')
  1672. console.debug('ShowMetacriticRatings: TV title from English page:', parts[parts.length - 1])
  1673. return parts[parts.length - 1]
  1674. } else if (document.querySelector('script[type="application/ld+json"]')) {
  1675. const ld = parseLDJSON(['name', 'alternateName'])
  1676. if (ld.length > 1 && ld[1]) {
  1677. console.debug('ShowMetacriticRatings: TV ld+json alternateName', ld[1])
  1678. return ld[1]
  1679. }
  1680. console.debug('ShowMetacriticRatings: TV ld+json name', ld[0])
  1681. return ld[0]
  1682. } else {
  1683. console.debug('ShowMetacriticRatings: TV <title>', document.title.match(/(.+?)\s+(\(\d+\))? - IMDb/)[1])
  1684. return document.title.match(/(.+?)\s+\(TV/)[1]
  1685. }
  1686. }
  1687. }
  1688. ]
  1689. },
  1690. steam: {
  1691. host: ['store.steampowered.com'],
  1692. condition: () => document.querySelector('*[itemprop=name]'),
  1693. products: [{
  1694. condition: Always,
  1695. type: 'pcgame',
  1696. data: () => document.querySelector('*[itemprop=name]').textContent
  1697. }]
  1698. },
  1699. rottentomatoes: {
  1700. host: ['rottentomatoes.com'],
  1701. condition: Always,
  1702. products: [{
  1703. condition: () => document.location.pathname.startsWith('/m/'),
  1704. type: 'movie',
  1705. data: () => document.querySelector('h1').firstChild.textContent
  1706. },
  1707. {
  1708. condition: () => document.location.pathname.startsWith('/tv/'),
  1709. type: 'tv',
  1710. data: () => unsafeWindow.BK.TvSeriesTitle
  1711. }
  1712. ]
  1713. },
  1714. serienjunkies: {
  1715. host: ['www.serienjunkies.de'],
  1716. condition: Always,
  1717. products: [{
  1718. condition: () => Always,
  1719. type: 'tv',
  1720. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  1721. }]
  1722. },
  1723. gamespot: {
  1724. host: ['gamespot.com'],
  1725. condition: () => document.querySelector('[itemprop=device]'),
  1726. products: [
  1727. {
  1728. condition: () => ~$('[itemprop=device]').text().indexOf('PC'),
  1729. type: 'pcgame',
  1730. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  1731. },
  1732. {
  1733. condition: () => ~$('[itemprop=device]').text().indexOf('PS4'),
  1734. type: 'ps4game',
  1735. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  1736. },
  1737. {
  1738. condition: () => ~$('[itemprop=device]').text().indexOf('XONE'),
  1739. type: 'xonegame',
  1740. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  1741. }
  1742. ]
  1743. },
  1744. amazon: {
  1745. host: ['amazon.'],
  1746. condition: Always,
  1747. products: [
  1748. {
  1749. condition: () => document.location.hostname === 'music.amazon.com' && document.location.pathname.startsWith('/albums/') && document.querySelector('.viewTitle'), // "Amazon Music Unlimited" page
  1750. type: 'music',
  1751. data: function () {
  1752. const artist = document.querySelector('.artistLink').textContent.trim()
  1753. let title = document.querySelector('.viewTitle').textContent.trim()
  1754. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  1755. if (artist && title) {
  1756. return [artist, title]
  1757. }
  1758. return false
  1759. }
  1760. },
  1761. {
  1762. condition: function () { // "Normal amazon" page
  1763. try {
  1764. if (document.querySelector('.nav-categ-image').alt.toLowerCase().indexOf('musi') !== -1) {
  1765. return true
  1766. }
  1767. } catch (e) {}
  1768. const music = ['Music', 'Musique', 'Musik', 'Música', 'Musica', '音楽']
  1769. return music.some(function (s) {
  1770. if (~document.title.indexOf(s)) {
  1771. return true
  1772. } else {
  1773. return false
  1774. }
  1775. })
  1776. },
  1777. type: 'music',
  1778. data: function () {
  1779. let artist = false
  1780. let title = false
  1781. if (document.querySelector('#ProductInfoArtistLink')) {
  1782. artist = document.querySelector('#ProductInfoArtistLink').textContent.trim()
  1783. } else if (document.querySelector('#bylineInfo .author>*')) {
  1784. artist = document.querySelector('#bylineInfo .author>*').textContent.trim()
  1785. }
  1786.  
  1787. if (document.querySelector('#dmusicProductTitle_feature_div')) {
  1788. title = document.querySelector('#dmusicProductTitle_feature_div').textContent.trim()
  1789. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  1790. } else if (document.querySelector('#productTitle')) {
  1791. title = document.querySelector('#productTitle').textContent.trim()
  1792. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  1793. }
  1794. return [artist, title]
  1795. }
  1796. },
  1797. {
  1798. condition: () => (document.querySelector('[data-automation-id=title]') && (
  1799. document.getElementsByClassName('av-season-single').length ||
  1800. document.querySelector('[data-automation-id="num-of-seasons-badge"]') ||
  1801. document.getElementById('tab-selector-episodes') ||
  1802. document.getElementById('av-droplist-av-atf-season-selector')
  1803. )),
  1804. type: 'tv',
  1805. data: () => document.querySelector('[data-automation-id=title]').textContent.trim()
  1806. },
  1807. {
  1808. condition: () => ((
  1809. document.getElementsByClassName('av-season-single').length ||
  1810. document.querySelector('[data-automation-id="num-of-seasons-badge"]') ||
  1811. document.getElementById('tab-selector-episodes') ||
  1812. document.getElementById('av-droplist-av-atf-season-selector')
  1813. ) && Array.from(document.querySelectorAll('script[type="text/template"]')).map(e => e.innerHTML.match(/parentTitle"\s*:\s*"(.+?)"/)).some((x) => x != null)),
  1814. type: 'tv',
  1815. data: () => Array.from(document.querySelectorAll('script[type="text/template"]')).map(e => e.innerHTML.match(/parentTitle"\s*:\s*"(.+?)"/)).filter((x) => x != null)[0][1]
  1816. },
  1817. {
  1818. condition: () => document.querySelector('[data-automation-id=title]'),
  1819. type: 'movie',
  1820. data: () => document.querySelector('[data-automation-id=title]').textContent.trim().replace(/\[.{1,8}\]/, '')
  1821. }
  1822. ]
  1823. },
  1824. BoxOfficeMojo: {
  1825. host: ['boxofficemojo.com'],
  1826. condition: () => Always,
  1827. products: [
  1828. {
  1829. condition: () => document.location.pathname.startsWith('/release/'),
  1830. type: 'movie',
  1831. data: () => document.querySelector('meta[name=title]').content
  1832. },
  1833. {
  1834. // Old page design
  1835. condition: () => ~document.location.search.indexOf('id=') && document.querySelector('#body table:nth-child(2) tr:first-child b'),
  1836. type: 'movie',
  1837. data: () => document.querySelector('#body table:nth-child(2) tr:first-child b').firstChild.textContent
  1838. }]
  1839. },
  1840. AllMovie: {
  1841. host: ['allmovie.com'],
  1842. condition: () => document.querySelector('h2.movie-title'),
  1843. products: [{
  1844. condition: () => document.querySelector('h2.movie-title'),
  1845. type: 'movie',
  1846. data: () => document.querySelector('h2.movie-title').firstChild.textContent.trim()
  1847. }]
  1848. },
  1849. 'en.wikipedia': {
  1850. host: ['en.wikipedia.org'],
  1851. condition: Always,
  1852. products: [{
  1853. condition: function () {
  1854. if (!document.querySelector('.infobox .summary')) {
  1855. return false
  1856. }
  1857. const r = /\d\d\d\d films/
  1858. return $('#catlinks a').filter((i, e) => e.firstChild.textContent.match(r)).length
  1859. },
  1860. type: 'movie',
  1861. data: () => document.querySelector('.infobox .summary').firstChild.textContent
  1862. },
  1863. {
  1864. condition: function () {
  1865. if (!document.querySelector('.infobox .summary')) {
  1866. return false
  1867. }
  1868. const r = /television series/
  1869. return $('#catlinks a').filter((i, e) => e.firstChild.textContent.match(r)).length
  1870. },
  1871. type: 'tv',
  1872. data: () => document.querySelector('.infobox .summary').firstChild.textContent
  1873. }]
  1874. },
  1875. fandango: {
  1876. host: ['fandango.com'],
  1877. condition: () => document.querySelector("meta[property='og:title']"),
  1878. products: [{
  1879. condition: Always,
  1880. type: 'movie',
  1881. data: () => document.querySelector("meta[property='og:title']").content.match(/(.+?)\s+\(\d{4}\)/)[1].trim()
  1882. }]
  1883. },
  1884. flixster: {
  1885. host: ['www.flixster.com'],
  1886. condition: () => Always,
  1887. products: [{
  1888. condition: () => parseLDJSON('@type') === 'Movie',
  1889. type: 'movie',
  1890. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  1891. }]
  1892. },
  1893. themoviedb: {
  1894. host: ['themoviedb.org'],
  1895. condition: () => document.querySelector("meta[property='og:type']"),
  1896. products: [{
  1897. condition: () => document.querySelector("meta[property='og:type']").content === 'movie',
  1898. type: 'movie',
  1899. data: () => document.querySelector("meta[property='og:title']").content
  1900. },
  1901. {
  1902. condition: () => document.querySelector("meta[property='og:type']").content === 'tv' || document.querySelector("meta[property='og:type']").content === 'tv_series',
  1903. type: 'tv',
  1904. data: () => document.querySelector("meta[property='og:title']").content
  1905. }]
  1906. },
  1907. letterboxd: {
  1908. host: ['letterboxd.com'],
  1909. condition: () => unsafeWindow.filmData && 'name' in unsafeWindow.filmData,
  1910. products: [{
  1911. condition: Always,
  1912. type: 'movie',
  1913. data: () => unsafeWindow.filmData.name
  1914. }]
  1915. },
  1916. TVmaze: {
  1917. host: ['tvmaze.com'],
  1918. condition: () => document.querySelector('h1'),
  1919. products: [{
  1920. condition: Always,
  1921. type: 'tv',
  1922. data: () => document.querySelector('h1').firstChild.textContent
  1923. }]
  1924. },
  1925. TVGuide: {
  1926. host: ['tvguide.com'],
  1927. condition: Always,
  1928. products: [{
  1929. condition: () => document.location.pathname.startsWith('/tvshows/'),
  1930. type: 'tv',
  1931. data: function () {
  1932. if (document.querySelector('meta[itemprop=name]')) {
  1933. return document.querySelector('meta[itemprop=name]').content
  1934. } else {
  1935. return document.querySelector("meta[property='og:title']").content.split('|')[0]
  1936. }
  1937. }
  1938. }]
  1939. },
  1940. followshows: {
  1941. host: ['followshows.com'],
  1942. condition: Always,
  1943. products: [{
  1944. condition: () => document.querySelector("meta[property='og:type']").content === 'video.tv_show',
  1945. type: 'tv',
  1946. data: () => document.querySelector("meta[property='og:title']").content
  1947. }]
  1948. },
  1949. TheTVDB: {
  1950. host: ['thetvdb.com'],
  1951. condition: Always,
  1952. products: [{
  1953. condition: () => document.location.pathname.startsWith('/series/'),
  1954. type: 'tv',
  1955. data: () => document.getElementById('series_title').firstChild.textContent.trim()
  1956. },
  1957. {
  1958. condition: () => document.location.pathname.startsWith('/movies/'),
  1959. type: 'movie',
  1960. data: () => document.getElementById('series_title').firstChild.textContent.trim()
  1961. }]
  1962. },
  1963. ConsequenceOfSound: {
  1964. host: ['consequence.net', 'consequenceofsound.net'],
  1965. condition: () => document.querySelector('#main-content .review-summary'),
  1966. products: [
  1967. {
  1968. condition: () => document.querySelector('meta[name="cXenseParse:cns-artist-names"]') && document.querySelector('em'),
  1969. type: 'music',
  1970. data: function () {
  1971. window.setInterval(function () {
  1972. if (document.getElementById('ot-sdk-btn-floating')) {
  1973. document.getElementById('ot-sdk-btn-floating').remove()
  1974. }
  1975. }, 5000)
  1976. const artist = document.querySelector('meta[name="cXenseParse:cns-artist-names"]').content
  1977. const arr = Array.from(document.querySelectorAll('em')).map((em) => em.textContent.trim())
  1978. const counts = {}
  1979. for (const num of arr) {
  1980. counts[num] = counts[num] ? counts[num] + 1 : 1
  1981. }
  1982. const max = Math.max(...Object.values(counts))
  1983. const maxIndex = Object.values(counts).indexOf(max)
  1984. const title = Object.keys(counts)[maxIndex]
  1985. return [artist, title]
  1986. }
  1987. },
  1988. {
  1989. condition: () => document.title.match(/'(.*?)'\s*Album/i) && document.querySelector('meta[name="cXenseParse:cns-artist-names"]'),
  1990. type: 'music',
  1991. data: function () {
  1992. window.setInterval(function () {
  1993. if (document.getElementById('ot-sdk-btn-floating')) {
  1994. document.getElementById('ot-sdk-btn-floating').remove()
  1995. }
  1996. }, 5000)
  1997. const title = document.title.match(/'(.*?)'\s*Album/i)[1]
  1998. const artist = document.querySelector('meta[name="cXenseParse:cns-artist-names"]').content
  1999. return [artist, title]
  2000. }
  2001. },
  2002. {
  2003. condition: () => document.title.match(/(.+?)\s+\u2013\s+(.+?) \| Album Review/),
  2004. type: 'music',
  2005. data: function () {
  2006. window.setInterval(function () {
  2007. if (document.getElementById('ot-sdk-btn-floating')) {
  2008. document.getElementById('ot-sdk-btn-floating').remove()
  2009. }
  2010. }, 5000)
  2011. const m = document.title.match(/(.+?)\s+\u2013\s+(.+?) \| Album Review/)
  2012. return [m[1], m[2]]
  2013. }
  2014. },
  2015. {
  2016. condition: () => document.location.pathname.indexOf('/album-review') !== -1 && document.querySelector('a.tag[href*="/artist/"'),
  2017. type: 'music',
  2018. data: function () {
  2019. window.setInterval(function () {
  2020. if (document.getElementById('ot-sdk-btn-floating')) {
  2021. document.getElementById('ot-sdk-btn-floating').remove()
  2022. }
  2023. }, 5000)
  2024. const artistAndTitleWithDash = document.location.pathname.match(/album-review-([\w-]+)/)[1]
  2025. const artistWithDash = document.querySelector('a.tag[href*="/artist/"').pathname.match(/artist\/([\w-]+)/)[1]
  2026. const titleWithDash = artistAndTitleWithDash.replace(artistWithDash, '')
  2027. const title = titleWithDash.replace('-', ' ').trim()
  2028. const artist = artistWithDash.replace('-', ' ').trim()
  2029. return [artist, title]
  2030. }
  2031. }]
  2032. },
  2033. Pitchfork: {
  2034. host: ['pitchfork.com'],
  2035. condition: () => ~document.location.href.indexOf('/reviews/albums/'),
  2036. products: [{
  2037. condition: () => document.querySelector('.single-album-tombstone'),
  2038. type: 'music',
  2039. data: function () {
  2040. let artist
  2041. let album
  2042. if (document.querySelector('.single-album-tombstone .artists')) {
  2043. artist = document.querySelector('.single-album-tombstone .artists').innerText.trim()
  2044. } else if (document.querySelector('.single-album-tombstone .artist-list')) {
  2045. artist = document.querySelector('.single-album-tombstone .artist-list').innerText.trim()
  2046. }
  2047. if (document.querySelector('.single-album-tombstone h1.review-title')) {
  2048. album = document.querySelector('.single-album-tombstone h1.review-title').innerText.trim()
  2049. } else if (document.querySelector('.single-album-tombstone h1')) {
  2050. album = document.querySelector('.single-album-tombstone h1').innerText.trim()
  2051. }
  2052.  
  2053. return [artist, album]
  2054. }
  2055. }]
  2056. },
  2057. 'Last.fm': {
  2058. host: ['last.fm'],
  2059. condition: () => document.querySelector('*[data-page-resource-type]') && document.querySelector('*[data-page-resource-type]').dataset.pageResourceType === 'album',
  2060. products: [{
  2061. condition: () => document.querySelector('*[data-page-resource-type]').dataset.pageResourceName,
  2062. type: 'music',
  2063. data: function () {
  2064. const artist = document.querySelector('*[data-page-resource-type]').dataset.pageResourceArtistName
  2065. const album = document.querySelector('*[data-page-resource-type]').dataset.pageResourceName
  2066. return [artist, album]
  2067. }
  2068. }]
  2069. },
  2070. TVNfo: {
  2071. host: ['tvnfo.com'],
  2072. condition: () => document.querySelector('.ui.breadcrumb a[href*="/series"]'),
  2073. products: [{
  2074. condition: Always,
  2075. type: 'tv',
  2076. data: function () {
  2077. const years = document.querySelector('#title h1 .years').textContent.trim()
  2078. const title = document.querySelector('#title h1').textContent.replace(years, '').trim()
  2079. return title
  2080. }
  2081. }]
  2082. },
  2083. rateyourmusic: {
  2084. host: ['rateyourmusic.com'],
  2085. condition: () => document.querySelector("meta[property='og:type']"),
  2086. products: [{
  2087. condition: () => document.querySelector("meta[property='og:type']").content === 'music.album',
  2088. type: 'music',
  2089. data: function () {
  2090. const artist = document.querySelector('.section_main_info .artist').innerText.trim()
  2091. const album = document.querySelector('.section_main_info .album_title').innerText.trim()
  2092. return [artist, album]
  2093. }
  2094. }]
  2095. },
  2096. spotify: {
  2097. host: ['open.spotify.com'],
  2098. condition: Always,
  2099. products: [{
  2100. condition: () => document.location.pathname.startsWith('/album/') && document.querySelector('.Root__main-view h1'),
  2101. type: 'music',
  2102. data: function () {
  2103. const album = document.querySelector('.Root__main-view h1').textContent.trim()
  2104. let artist = []
  2105. document.querySelector('.Root__main-view h1').parentNode.parentNode.parentNode.querySelectorAll('a[href*="/artist/"]').forEach(function (a) {
  2106. artist.push(a.textContent.trim())
  2107. })
  2108. artist = artist.join(' ')
  2109. return [artist, album]
  2110. }
  2111. }]
  2112. },
  2113. nme: {
  2114. host: ['nme.com'],
  2115. condition: () => document.location.pathname.startsWith('/reviews/'),
  2116. products: [
  2117. {
  2118. condition: () => document.querySelector('.tdb-breadcrumbs a[href*="/reviews/film-reviews"]'),
  2119. type: 'movie',
  2120. data: function () {
  2121. try {
  2122. return document.title.match(/[‘'](.+?)[’']/)[1]
  2123. } catch (e) {
  2124. try {
  2125. return document.querySelector('h1.tdb-title-text').textContent.match(/[‘'](.+?)[’']/)[1]
  2126. } catch (e) {
  2127. return document.querySelector('h1').textContent.match(/:\s*(.+)/)[1].trim()
  2128. }
  2129. }
  2130. }
  2131. },
  2132. {
  2133. condition: () => document.querySelector('#nme-music-header'),
  2134. type: 'music',
  2135. data: () => document.querySelector('h1.tdb-title-text').textContent.match(/\s*(.+?)\s*.\s*[‘'](.+?)[’']/).slice(1)
  2136. },
  2137. {
  2138. condition: () => document.querySelector('.tdb-breadcrumbs a[href*="/reviews/tv-reviews"]'),
  2139. type: 'tv',
  2140. data: () => document.querySelector('h1.tdb-title-text').textContent.match(/[‘'](.+?)[’']/)[1]
  2141. }]
  2142. },
  2143. albumoftheyear: {
  2144. host: ['albumoftheyear.org'],
  2145. condition: Always,
  2146. products: [{
  2147. condition: () => document.location.pathname.startsWith('/album/'),
  2148. type: 'music',
  2149. data: function () {
  2150. const artist = document.querySelector('*[itemprop=byArtist] *[itemprop=name]').textContent
  2151. const album = document.querySelector('.albumTitle *[itemprop=name]').textContent
  2152. return [artist, album]
  2153. }
  2154. }]
  2155. },
  2156. epguides: {
  2157. host: ['epguides.com'],
  2158. condition: () => document.getElementById('eplist'),
  2159. products: [{
  2160. condition: () => document.getElementById('eplist') && document.querySelector('.center.titleblock h2'),
  2161. type: 'tv',
  2162. data: () => document.querySelector('.center.titleblock h2').textContent.trim()
  2163. }]
  2164. },
  2165. ShareTV: {
  2166. host: ['sharetv.com'],
  2167. condition: () => document.location.pathname.startsWith('/shows/'),
  2168. products: [{
  2169. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:title']"),
  2170. type: 'tv',
  2171. data: () => document.querySelector("meta[property='og:title']").content
  2172. }]
  2173. },
  2174. /*
  2175. netflix: {
  2176. host: ['netflix.com'],
  2177. condition: !(document.querySelector('.button-nfplayerPlay') || document.querySelector('.nf-big-play-pause') || document.querySelector('.AkiraPlayer video')),
  2178.  
  2179. // TODO
  2180. // https://www.netflix.com/de/title/70264888
  2181. // https://www.netflix.com/de/title/70178217
  2182. // https://www.netflix.com/de/title/70305892 ## Movie
  2183. // https://www.netflix.com/de-en/title/80108495 ## No meta
  2184.  
  2185. products: [{
  2186. condition: () => parseLDJSON('@type') === 'Movie',
  2187. type: 'movie',
  2188. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2189. },
  2190. {
  2191. condition: () => parseLDJSON('@type') === 'TVSeries',
  2192. type: 'tv',
  2193. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  2194. }]
  2195. },
  2196. */
  2197. ComedyCentral: {
  2198. host: ['cc.com'],
  2199. condition: () => document.location.pathname.startsWith('/shows/'),
  2200. products: [{
  2201. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:title']"),
  2202. type: 'tv',
  2203. data: () => document.querySelector("meta[property='og:title']").content.replace('| Comedy Central', '').trim()
  2204. },
  2205. {
  2206. condition: () => document.location.pathname.split('/').length === 3 && document.title.match(/(.+?)\s+-\s+Series/),
  2207. type: 'tv',
  2208. data: () => document.title.match(/(.+?)\s+-\s+Series/)[1]
  2209. }]
  2210. },
  2211. TVHoard: {
  2212. host: ['tvhoard.com'],
  2213. condition: Always,
  2214. products: [{
  2215. condition: () => document.location.pathname.split('/').length === 3 && document.location.pathname.split('/')[1] === 'titles' && !document.querySelector('app-root title-secondary-details-panel .seasons') && document.querySelector('app-root title-page-container h1.title a'),
  2216. type: 'movie',
  2217. data: () => document.querySelector('app-root title-page-container h1.title a').textContent.trim()
  2218. },
  2219. {
  2220. condition: () => document.location.pathname.split('/').length === 3 && document.location.pathname.split('/')[1] === 'titles' && document.querySelector('app-root title-secondary-details-panel .seasons') && document.querySelector('app-root title-page-container h1.title a'),
  2221. type: 'tv',
  2222. data: () => document.querySelector('app-root title-page-container h1.title a').textContent.trim()
  2223. }]
  2224. },
  2225. AMC: {
  2226. host: ['amc.com'],
  2227. condition: () => document.location.pathname.startsWith('/shows/'),
  2228. products: [
  2229. {
  2230. condition: () => document.querySelector('.feeds[itemtype="http://schema.org/TVSeries"] h1'),
  2231. type: 'tv',
  2232. data: () => document.querySelector('.feeds[itemtype="http://schema.org/TVSeries"] h1').textContent
  2233. },
  2234. {
  2235. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:type']") && document.querySelector("meta[property='og:type']").content.indexOf('tv_show') !== -1,
  2236. type: 'tv',
  2237. data: () => document.querySelector('.video-card-description h1').textContent.trim()
  2238. }]
  2239. },
  2240. AMCplus: {
  2241. host: ['amcplus.com'],
  2242. condition: () => Always,
  2243. products: [
  2244. {
  2245. condition: () => document.title.match(/Watch .+? |/),
  2246. type: 'tv',
  2247. data: () => document.title.match(/Watch (.+?) |/)[1].trim()
  2248. }]
  2249. },
  2250. RlsBB: {
  2251. host: ['comment.rlsbb.ru'],
  2252. condition: () => document.querySelectorAll('.post').length === 1,
  2253. products: [
  2254. {
  2255. condition: () => document.querySelector('#post-wrapper .entry-meta a[href*="/category/movies/"]'),
  2256. type: 'movie',
  2257. data: () => document.querySelector('h1.entry-title').textContent.match(/(.+?)\s+\d{4}/)[1].trim()
  2258. },
  2259. {
  2260. condition: () => document.querySelector('#post-wrapper .entry-meta a[href*="/category/tv-shows/"]'),
  2261. type: 'tv',
  2262. data: () => document.querySelector('h1.entry-title').textContent.match(/(.+?)\s+S\d{2}/)[1].trim()
  2263. }]
  2264. },
  2265. newalbumreleases: {
  2266. host: ['newalbumreleases.net'],
  2267. condition: () => document.querySelectorAll('#content .single').length === 1,
  2268. products: [
  2269. {
  2270. condition: () => document.querySelector('#content .single .cover .entry'),
  2271. type: 'music',
  2272. data: function () {
  2273. const mArtist = document.querySelector('#content .single .cover .entry').textContent.match(/Artist.\s*(.+)\s+/i)
  2274. if (mArtist) {
  2275. const mAlbum = document.querySelector('#content .single .cover .entry').textContent.match(/Album.\s*(.+)\s+/i)
  2276. if (mAlbum) {
  2277. return [mArtist[1], mAlbum[1]]
  2278. }
  2279. }
  2280. }
  2281. }]
  2282. },
  2283. showtime: {
  2284. host: ['sho.com'],
  2285. condition: Always,
  2286. products: [
  2287. {
  2288. condition: () => parseLDJSON('@type') === 'Movie',
  2289. type: 'movie',
  2290. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2291. },
  2292. {
  2293. condition: () => parseLDJSON('@type') === 'TVSeries',
  2294. type: 'tv',
  2295. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  2296. }]
  2297. },
  2298. epicgames: {
  2299. host: ['www.epicgames.com', 'store.epicgames.com'],
  2300. condition: () => document.querySelector('.meta-schema'),
  2301. products: [{
  2302. condition: Always,
  2303. type: 'pcgame',
  2304. data: () => document.querySelector('.meta-schema').nextElementSibling.firstElementChild.lastElementChild.firstElementChild.firstElementChild.firstElementChild.textContent
  2305. }]
  2306. },
  2307. gog: {
  2308. host: ['www.gog.com'],
  2309. condition: () => document.querySelector('.productcard-basics__title'),
  2310. products: [
  2311. {
  2312. condition: () => document.location.pathname.slice(1, 5) === 'game',
  2313. type: 'pcgame',
  2314. data: () => document.querySelector('.productcard-basics__title').textContent
  2315. },
  2316. {
  2317. condition: () => document.location.pathname.slice(1, 6) === 'movie',
  2318. type: 'movie',
  2319. data: () => document.querySelector('.productcard-basics__title').textContent
  2320. }
  2321. ]
  2322. },
  2323. steamgifts: {
  2324. host: ['www.steamgifts.com'],
  2325. condition: () => document.querySelector('.featured__heading__medium'),
  2326. products: [{
  2327. condition: Always,
  2328. type: 'pcgame',
  2329. data: () => document.querySelector('.featured__heading__medium').innerText
  2330. }]
  2331. },
  2332. allmusic: {
  2333. host: ['allmusic.com'],
  2334. condition: Always,
  2335. products: [{
  2336. condition: () => document.location.pathname.indexOf('/album/') !== -1,
  2337. type: 'music',
  2338. data: function () {
  2339. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  2340. const album = ld[0]
  2341. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  2342. return [artist, album]
  2343. }
  2344. }]
  2345. },
  2346. psapm: {
  2347. host: ['psa.pm'],
  2348. condition: Always,
  2349. products: [
  2350. {
  2351. condition: () => document.location.pathname.startsWith('/movie/'),
  2352. type: 'movie',
  2353. data: function () {
  2354. const title = document.querySelector('h1').textContent.trim()
  2355. const m = title.match(/(.+)\((\d+)\)$/)
  2356. if (m) {
  2357. return m[1].trim()
  2358. } else {
  2359. return title
  2360. }
  2361. }
  2362. },
  2363. {
  2364. condition: () => document.location.pathname.startsWith('/tv-show/'),
  2365. type: 'tv',
  2366. data: () => document.querySelector('h1').textContent.trim()
  2367. }
  2368. ]
  2369. },
  2370. 'save.tv': {
  2371. host: ['save.tv'],
  2372. condition: () => document.location.pathname.startsWith('/STV/M/obj/archive/'),
  2373. products: [
  2374. {
  2375. condition: () => document.location.pathname.startsWith('/STV/M/obj/archive/'),
  2376. type: 'movie',
  2377. data: function () {
  2378. let title = null
  2379. if (document.querySelector("span[data-bind='text:OrigTitle']")) {
  2380. title = document.querySelector("span[data-bind='text:OrigTitle']").textContent
  2381. } else {
  2382. title = document.querySelector("h2[data-bind='text:Title']").textContent
  2383. }
  2384. let year = null
  2385. if (document.querySelector("span[data-bind='text:ProductionYear']")) {
  2386. year = parseInt(document.querySelector("span[data-bind='text:ProductionYear']").textContent)
  2387. }
  2388. return [title, year]
  2389. }
  2390. }
  2391. ]
  2392. },
  2393. aRGENTeaM: {
  2394. host: ['argenteam.net'],
  2395. condition: Always,
  2396. products: [
  2397. {
  2398. condition: () => document.location.pathname.startsWith('/movie/'),
  2399. type: 'movie',
  2400. data: function () {
  2401. const partes = document.title.split('•')
  2402. const SinArgenteam = partes[1].trim()
  2403. const SoloTitulo = SinArgenteam.split('(')[0].trim()
  2404. const Year = SinArgenteam.split('(')[1].split(')')[0]
  2405. return [SoloTitulo, Year]
  2406. }
  2407. },
  2408. {
  2409. condition: () => document.location.pathname.startsWith('/episode/'),
  2410. type: 'tv',
  2411. data: () => document.querySelector('.pserie h1').firstChild.textContent.trim()
  2412. }
  2413. ]
  2414. }
  2415.  
  2416. }
  2417.  
  2418. async function main () {
  2419. let dataFound = false
  2420.  
  2421. let map = false
  2422.  
  2423. for (const name in sites) {
  2424. const site = sites[name]
  2425. if (site.host.some(function (e) { return ~this.indexOf(e) }, document.location.hostname) && site.condition()) {
  2426. for (let i = 0; i < site.products.length; i++) {
  2427. if (site.products[i].condition()) {
  2428. // Check map for a match
  2429. if (map === false) {
  2430. map = JSON.parse(await GM.getValue('map', '{}'))
  2431. }
  2432. const docurl = filterUniversalUrl(document.location.href)
  2433. if (docurl in map) {
  2434. // Found in map, show result
  2435. const metaurl = map[docurl]
  2436. metacriticGeneralProductSetup()
  2437. metacritic.mapped.apply(undefined, [docurl, site.products[i], absoluteMetaURL(metaurl), site.products[i].type])
  2438. dataFound = true
  2439. break
  2440. }
  2441. // Try to retrieve item name from page
  2442. let data
  2443. try {
  2444. data = await site.products[i].data()
  2445. } catch (e) {
  2446. data = false
  2447. console.error(`ShowMetacriticRatings: Error in data() of site='${name}', type='${site.products[i].type}'`)
  2448. console.error(e)
  2449. }
  2450. if (data) {
  2451. const params = [docurl, site.products[i]]
  2452. if (Array.isArray(data)) {
  2453. params.push(...data)
  2454. } else {
  2455. params.push(data)
  2456. }
  2457. metacriticGeneralProductSetup()
  2458. metacritic[site.products[i].type].apply(undefined, params)
  2459. dataFound = true
  2460. }
  2461. break
  2462. }
  2463. }
  2464. break
  2465. }
  2466. }
  2467. return dataFound
  2468. }
  2469.  
  2470. (async function () {
  2471. const gdpr = await acceptGDPR()
  2472. if (!gdpr) {
  2473. GM.registerMenuCommand('Show Metacritic.com ratings - Accept terms of service', () => acceptGDPR(true).then((yes) => yes && document.location.reload()))
  2474. return
  2475. }
  2476. await versionUpdate()
  2477. const firstRunResult = await main()
  2478.  
  2479. GM.registerMenuCommand('Show Metacritic.com ratings - Search now', () => openSearchBox())
  2480. GM.registerMenuCommand('Show Metacritic.com ratings - Change corner', () => changePosition())
  2481.  
  2482. let lastLoc = document.location.href
  2483. let lastContent = document.body.innerText
  2484. let lastCounter = 0
  2485. async function newpage () {
  2486. if (lastContent === document.body.innerText && lastCounter < 15) {
  2487. window.setTimeout(newpage, 500)
  2488. lastCounter++
  2489. } else {
  2490. lastContent = document.body.innerText
  2491. lastCounter = 0
  2492. const re = await main()
  2493. if (!re) { // No page matched or no data found
  2494. window.setTimeout(newpage, 1000)
  2495. }
  2496. }
  2497. }
  2498. window.setInterval(function () {
  2499. if (document.location.href !== lastLoc) {
  2500. lastLoc = document.location.href
  2501. $('#mcdiv123').remove()
  2502.  
  2503. window.setTimeout(newpage, 1000)
  2504. }
  2505. }, 500)
  2506.  
  2507. if (!firstRunResult) {
  2508. // Initial run had no match, let's try again there may be new content
  2509. window.setTimeout(main, 2000)
  2510. }
  2511. })()