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

目前为 2023-02-11 提交的版本,查看 最新版本

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