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

当前为 2022-10-15 提交的版本,查看 最新版本

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