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-16 提交的版本,查看 最新版本

  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 82
  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, failedImages */
  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 = /[-\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(function (resolve, reject) {
  563. isInRequestCache(data).then(function (cachedValue) {
  564. if (cachedValue) {
  565. return window.setTimeout(() => resolve(cachedValue), 10)
  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. data = Object.assign(defaultData, data)
  586. GM.xmlHttpRequest(data)
  587. })
  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. const newkey = JSON.stringify({
  835. url: requestData.url,
  836. method: requestData.method || 'GET',
  837. data: requestData.data || null
  838. })
  839. const cache = JSON.parse(await GM.getValue('requestcache', '{}'))
  840. const now = (new Date()).getTime()
  841. const timeout = 15 * 60 * 1000
  842. for (const prop in cache) {
  843. // Delete cached values, that are older than 15 minutes
  844. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  845. delete cache[prop]
  846. }
  847. }
  848.  
  849. const newobj = {}
  850. for (const key in response) {
  851. newobj[key] = response[key]
  852. }
  853. newobj.responseText = '' + response.responseText
  854. newobj.cached = true
  855. if (!('time' in newobj)) {
  856. newobj.time = (new Date()).toJSON()
  857. }
  858.  
  859. cache[newkey] = newobj
  860.  
  861. await GM.setValue('requestcache', JSON.stringify(cache))
  862. }
  863.  
  864. async function isInRequestCache (requestData) {
  865. const key = JSON.stringify({
  866. url: requestData.url,
  867. method: requestData.method || 'GET',
  868. data: requestData.data || null
  869. })
  870.  
  871. const cache = JSON.parse(await GM.getValue('requestcache', '{}'))
  872. const now = (new Date()).getTime()
  873. const timeout = 15 * 60 * 1000
  874. for (const prop in cache) {
  875. // Delete cached values, that are older than 15 minutes
  876. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  877. delete cache[prop]
  878. }
  879. }
  880.  
  881. if (key in cache) {
  882. return cache[key]
  883. } else {
  884. return false
  885. }
  886. }
  887.  
  888. async function storeInHoverCache (metaurl, response, orgMetaUrl) {
  889. const cache = JSON.parse(await GM.getValue('hovercache', '{}'))
  890. const now = (new Date()).getTime()
  891. const timeout = 2 * 60 * 60 * 1000
  892. for (const prop in cache) {
  893. // Delete cached values, that are older than 2 hours
  894. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  895. delete cache[prop]
  896. }
  897. }
  898.  
  899. const newobj = {}
  900. for (const key in response) {
  901. newobj[key] = response[key]
  902. }
  903. newobj.responseText = '' + response.responseText
  904. newobj.cached = true
  905. if (!('time' in newobj)) {
  906. newobj.time = (new Date()).toJSON()
  907. }
  908.  
  909. cache[metaurl] = newobj
  910. if (orgMetaUrl && orgMetaUrl !== metaurl) { // Store redirect
  911. cache[orgMetaUrl] = { time: (new Date()).toJSON(), redirect: metaurl }
  912. }
  913.  
  914. await GM.setValue('hovercache', JSON.stringify(cache))
  915. }
  916.  
  917. async function isInHoverCache (metaurl) {
  918. const cache = JSON.parse(await GM.getValue('hovercache', '{}'))
  919. const now = (new Date()).getTime()
  920. const timeout = 2 * 60 * 60 * 1000
  921. for (const prop in cache) {
  922. // Delete cached values, that are older than 2 hours
  923. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  924. delete cache[prop]
  925. }
  926. }
  927.  
  928. function resolveRedirects (cacheEntry) {
  929. if (cacheEntry.redirect) {
  930. const newkey = cacheEntry.redirect
  931. if (newkey in cache) {
  932. const value = cache[newkey]
  933. delete cache[newkey]
  934. return resolveRedirects(value)
  935. }
  936. } else {
  937. return cacheEntry
  938. }
  939. return false
  940. }
  941.  
  942. if (metaurl in cache) {
  943. const value = cache[metaurl]
  944. delete cache[metaurl]
  945. return resolveRedirects(value)
  946. } else {
  947. return false
  948. }
  949. }
  950.  
  951. async function loadHoverInfo () {
  952. const cacheResponse = await isInHoverCache(current.metaurl)
  953. if (cacheResponse !== false) {
  954. console.debug(`ShowMetacriticRatings: loadHoverInfo () ${current.metaurl} found in hover cache`)
  955. if (cacheResponse.responseText.indexOf('"jsonRedirect"') !== -1) {
  956. return await handleJSONredirect(cacheResponse)
  957. }
  958. return cacheResponse
  959. }
  960. const requestURL = baseURLdatabase
  961. const requestParams = 'm=' + encodeURIComponent(current.docurl) + '&a=' + encodeURIComponent(current.metaurl)
  962.  
  963. let response = await asyncRequest({
  964. method: 'POST',
  965. url: requestURL,
  966. data: requestParams,
  967. headers: {
  968. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  969. }
  970. }).catch(function (response) {
  971. console.warn('ShowMetacriticRatings: Error 02\nurl=' + requestURL + '\nparams=' + requestParams + '\nstatus=' + response.status)
  972. })
  973.  
  974. if (response.responseText && response.responseText.indexOf('"jsonRedirect"') !== -1) {
  975. response = await handleJSONredirect(response)
  976. }
  977.  
  978. if (response.status >= 500) {
  979. // Metacritic server error, try again after 2 seconds
  980. console.warn('ShowMetacriticRatings: Metacritic server error\nwait 2s for retry\nurl=' + current.metaurl + '\nstatus=' + response.status)
  981. await delay(2000)
  982. response = await asyncRequest({ url: current.metaurl }).catch(function (response) {
  983. console.warn('ShowMetacriticRatings: Error 06\nurl=' + current.metaurl + '\nstatus=' + response.status)
  984. })
  985. if (response.status > 300) {
  986. console.warn('ShowMetacriticRatings: Metacritic server error. Error 07. Retry failed as well.\nurl=' + current.metaurl + '\nstatus=' + response.status)
  987. } else {
  988. const newobj = {}
  989. for (const key in response) {
  990. newobj[key] = response[key]
  991. }
  992. newobj.responseText = extractHoverFromFullPage(response)
  993. response = newobj
  994. }
  995. }
  996.  
  997. if (response.responseText && response.responseText.indexOf('<title>500 Page') !== -1) {
  998. // Hover info not available for this url, try again with GET
  999. response = await asyncRequest({ url: current.metaurl }).catch(function (response) {
  1000. console.warn('ShowMetacriticRatings: Error 03\nurl=' + current.metaurl + '\nstatus=' + response.status)
  1001. })
  1002.  
  1003. const newobj = {}
  1004. for (const key in response) {
  1005. newobj[key] = response[key]
  1006. }
  1007. newobj.responseText = extractHoverFromFullPage(response)
  1008. response = newobj
  1009. }
  1010.  
  1011. if (!('time' in response)) {
  1012. response.time = (new Date()).toJSON()
  1013. }
  1014. if (response.status === 200 && response.responseText) {
  1015. return response
  1016. } else {
  1017. const error = new Error('ShowMetacriticRatings: loadHoverInfo()\nUrl: ' + response.finalUrl + '\nStatus: ' + response.status)
  1018. error.status = response.status
  1019. error.responseText = response.responseText
  1020. throw error
  1021. }
  1022. }
  1023.  
  1024. const current = {
  1025. metaurl: false,
  1026. docurl: false,
  1027. type: false,
  1028. data: [], // Array of raw search keys
  1029. searchTerm: false,
  1030. product: null,
  1031. broadenCounter: 0
  1032. }
  1033.  
  1034. async function loadMetacriticUrl (fromSearch) {
  1035. if (!current.metaurl) {
  1036. alert('ShowMetacriticRatings: Error 04')
  1037. return
  1038. }
  1039. const orgMetaUrl = current.metaurl
  1040. if (await isBlacklistedUrl(document.location.href, current.metaurl)) {
  1041. waitForHotkeysMETA()
  1042. return
  1043. }
  1044.  
  1045. if (await isTemporaryBlacklisted(current.metaurl)) {
  1046. console.debug(`ShowMetacriticRatings: loadMetacriticUrl(fromSearch=${fromSearch}) ${current.metaurl} is temporary blacklisted`)
  1047. waitForHotkeysMETA()
  1048. return
  1049. }
  1050.  
  1051. const response = await loadHoverInfo().catch(async function (response) {
  1052. if (response instanceof Error || (response && response.stack && response.message)) {
  1053. if (!fromSearch && ('status' in response && response.status === 404)) {
  1054. console.debug('ShowMetacriticRatings: loadMetacriticUrl(): status=404')
  1055. // No results
  1056. let broadenFct = broadenSearch // global broadenSearch function is the default
  1057. if ('broaden' in current.product) {
  1058. // try product 'broaden'-function if it is defined
  1059. broadenFct = current.product.broaden
  1060. }
  1061. const newData = await broadenFct(current.data.slice(0), ++current.broadenCounter, current.type)
  1062. if (JSON.stringify(newData) !== JSON.stringify(current.data)) {
  1063. current.data = newData
  1064. metacritic[current.type](current.docurl, current.product, ...newData)
  1065. } else if (JSON.stringify(newData) === JSON.stringify(current.data)) {
  1066. // Same data as before, try once again to broaden
  1067. const newData2 = await broadenFct(current.data.slice(0), ++current.broadenCounter, current.type)
  1068. if (JSON.stringify(newData2) !== JSON.stringify(current.data)) {
  1069. current.data = newData2
  1070. metacritic[current.type](current.docurl, current.product, ...newData2)
  1071. } else {
  1072. console.debug('ShowMetacriticRatings: loadMetacriticUrl(): ' + ('broaden' in current.product ? 'product specific' : 'global') + " 'broaden search' did not change after " + current.broadenCounter + ' steps')
  1073. }
  1074. } else {
  1075. console.debug("ShowMetacriticRatings: loadMetacriticUrl(): Unexpected result from 'broaden'-function: ", newData)
  1076. }
  1077. } else {
  1078. console.error(`ShowMetacriticRatings: loadMetacriticUrl(fromSearch=${fromSearch}) current.metaurl = ${current.metaurl}. Error in loadHoverInfo():\n`, response)
  1079. }
  1080. }
  1081.  
  1082. if (fromSearch) {
  1083. startSearch()
  1084. }
  1085. })
  1086.  
  1087. if (await isBlacklistedUrl(document.location.href, current.metaurl)) {
  1088. waitForHotkeysMETA()
  1089. return
  1090. }
  1091.  
  1092. if (typeof response !== 'undefined') {
  1093. showHoverInfo(response, orgMetaUrl)
  1094. } else {
  1095. waitForHotkeysMETA()
  1096. }
  1097. }
  1098.  
  1099. async function startSearch () {
  1100. waitForHotkeysMETA()
  1101.  
  1102. const cache = JSON.parse(await GM.getValue('autosearchcache', '{}'))
  1103. const now = (new Date()).getTime()
  1104. const timeout = 2 * 60 * 60 * 1000
  1105. for (const prop in cache) {
  1106. // Delete cached values, that are older than 2 hours
  1107. if (now - (new Date(cache[prop].time)).getTime() > timeout) {
  1108. delete cache[prop]
  1109. }
  1110. }
  1111.  
  1112. if (current.type === 'music') {
  1113. current.searchTerm = current.data[0]
  1114. } else {
  1115. current.searchTerm = current.data.join(' ')
  1116. }
  1117. let response
  1118. if (current.searchTerm in cache) {
  1119. response = cache[current.searchTerm]
  1120. } else {
  1121. response = await asyncRequest({
  1122. method: 'POST',
  1123. url: baseURLautosearch,
  1124. data: 'search_term=' + encodeURIComponent(current.searchTerm) + '&image_size=98&search_each=1&sort_type=popular',
  1125. headers: {
  1126. Referer: current.metaurl,
  1127. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  1128. // Host: 'www.metacritic.com',
  1129. 'User-Agent': 'MetacriticUserscript Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0',
  1130. 'X-Requested-With': 'XMLHttpRequest'
  1131. }
  1132. })
  1133. response = {
  1134. time: (new Date()).toJSON(),
  1135. json: JSON.parse(response.responseText)
  1136. }
  1137. cache[current.searchTerm] = response
  1138. await GM.setValue('autosearchcache', JSON.stringify(cache))
  1139. }
  1140.  
  1141. if (!response || !('json' in response)) {
  1142. alert('ShowMetacriticRatings: Error 05')
  1143. }
  1144. const data = response.json
  1145. let multiple = false
  1146. if (data && data.autoComplete && data.autoComplete.results && data.autoComplete.results.length) {
  1147. // Remove data with wrong type
  1148. data.autoComplete = data.autoComplete.results
  1149.  
  1150. const newdata = []
  1151. data.autoComplete.forEach(function (result) {
  1152. if (metacritic2searchType(result.refType) === current.type) {
  1153. newdata.push(result)
  1154. }
  1155. })
  1156. data.autoComplete = newdata
  1157. if (data.autoComplete.length === 0) {
  1158. // No results
  1159. console.debug('ShowMetacriticRatings: No results (after filtering by type) for searchTerm=' + current.searchTerm)
  1160. } else if (data.autoComplete.length === 1) {
  1161. // One result, let's show it
  1162. if (!await isBlacklistedUrl(document.location.href, absoluteMetaURL(data.autoComplete[0].url))) {
  1163. current.metaurl = absoluteMetaURL(data.autoComplete[0].url)
  1164. loadMetacriticUrl(true)
  1165. return
  1166. }
  1167. } else {
  1168. // More than one result
  1169. multiple = true
  1170. console.debug('ShowMetacriticRatings: Multiple results for searchTerm=' + current.searchTerm)
  1171. const exactMatches = []
  1172. data.autoComplete.forEach(function (result, i) { // Try to find the correct result by matching the search term to exactly one movie title
  1173. if (current.searchTerm === result.name) {
  1174. exactMatches.push(result)
  1175. }
  1176. })
  1177. if (exactMatches.length === 1) {
  1178. // Only one exact match, let's show it
  1179. console.debug('ShowMetacriticRatings: Only one exact match for searchTerm=' + current.searchTerm)
  1180. if (!await isBlacklistedUrl(document.location.href, absoluteMetaURL(exactMatches[0].url))) {
  1181. current.metaurl = absoluteMetaURL(exactMatches[0].url)
  1182. loadMetacriticUrl(true)
  1183. return
  1184. }
  1185. }
  1186. }
  1187. } else {
  1188. console.debug('ShowMetacriticRatings: No results (at all) for searchTerm=' + current.searchTerm)
  1189. }
  1190. // HERE: multiple results or no result. The user may type "meta" now
  1191. if (multiple) {
  1192. balloonAlert('Multiple metacritic results. Type &#34;meta&#34; for manual search.', 10000, false, { bottom: 5, top: 'auto', maxWidth: 400, paddingRight: 5 }, () => openSearchBox(true))
  1193. }
  1194. }
  1195.  
  1196. function openSearchBox (search) {
  1197. let query
  1198. if (current.type === 'music') {
  1199. query = current.data[0]
  1200. } else {
  1201. query = current.data.join(' ')
  1202. }
  1203. $('#mcdiv123').remove()
  1204. const div = $('<div id="mcdiv123"></div>').appendTo(document.body)
  1205. div.css({
  1206. position: 'fixed',
  1207. bottom: 0,
  1208. left: 0,
  1209. minWidth: 300,
  1210. maxHeight: '80%',
  1211. maxWidth: 640,
  1212. overflow: 'auto',
  1213. backgroundColor: '#fff',
  1214. border: '2px solid #bbb',
  1215. borderRadius: ' 6px',
  1216. boxShadow: '0 0 3px 3px rgba(100, 100, 100, 0.2)',
  1217. color: '#000',
  1218. padding: ' 3px',
  1219. zIndex: '2147483601'
  1220. })
  1221. $('<input type="text" size="60" id="mcisearchquery" style="background:white;color:black;">').appendTo(div).focus().val(query).on('keypress', function (e) {
  1222. const code = e.keyCode || e.which
  1223. if (code === 13) { // Enter key
  1224. searchBoxSearch(e, $('#mcisearchquery').val())
  1225. }
  1226. })
  1227. $('<button id="mcisearchbutton" style="background:silver;color:black;">').text('Search').appendTo(div).click((ev) => searchBoxSearch(ev, $('#mcisearchquery').val()))
  1228. }
  1229. async function searchBoxSearch (ev, query) {
  1230. if (!query) { // Use values from search form
  1231. query = current.searchTerm
  1232. }
  1233.  
  1234. const type = searchType2metacritic(current.type)
  1235.  
  1236. const style = document.createElement('style')
  1237. style.type = 'text/css'
  1238. style.innerHTML = CSS
  1239. document.head.appendChild(style)
  1240.  
  1241. const div = $('#mcdiv123')
  1242. const loader = $('<div style="width:20px; height:20px;display:inline-block" class="grespinner"></div>').appendTo($('#mcisearchbutton'))
  1243.  
  1244. const url = baseURLsearch.replace('{type}', encodeURIComponent(type)).replace('{query}', encodeURIComponent(query))
  1245.  
  1246. const response = await asyncRequest({
  1247. url,
  1248. data: 'search_term=' + encodeURIComponent(current.searchTerm) + '&image_size=98&search_each=1&sort_type=popular',
  1249. headers: {
  1250. Referer: url,
  1251. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  1252. // Host: 'www.metacritic.com',
  1253. 'User-Agent': 'MetacriticUserscript ' + navigator.userAgent
  1254. }
  1255. }).catch(function (response) {
  1256. alert('Search failed!\n' + response.finalUrl + '\nStatus: ' + response.status + '\n' + response.responseText ? response.responseText.substring(0, 500) : 'Empty response')
  1257. })
  1258.  
  1259. const results = []
  1260. if (!~response.responseText.indexOf('No search results found.')) {
  1261. const d = $('<html>').html(response.responseText)
  1262. d.find('ul.search_results.module .result').each(function () {
  1263. results.push(this.innerHTML)
  1264. })
  1265. }
  1266.  
  1267. if (results && results.length > 0) {
  1268. // Show results
  1269. loader.remove()
  1270.  
  1271. const accept = function (ev) {
  1272. const parentDiv = $(this.parentNode)
  1273. const a = parentDiv.find("a[href*='metacritic.com']")
  1274. const metaurl = a.attr('href')
  1275. const docurl = document.location.href
  1276.  
  1277. const resultDivParent = parentDiv.parent()
  1278. resultDivParent.html('')
  1279. resultDivParent.append(loader)
  1280.  
  1281. removeFromBlacklist(docurl, metaurl).then(function () {
  1282. addToMap(docurl, metaurl).then(function () {
  1283. current.metaurl = metaurl
  1284. loadMetacriticUrl().then(() => loader.remove())
  1285. })
  1286. })
  1287. }
  1288. const denyAll = function (ev) {
  1289. const docurl = document.location.href
  1290. $('#mcdiv123searchresults').find("div.result a[href*='metacritic.com']").each(function () {
  1291. addToBlacklist(docurl, this.href)
  1292. })
  1293. }
  1294.  
  1295. const resultdiv = $('#mcdiv123searchresults').length ? $('#mcdiv123searchresults').html('') : $('<div id="mcdiv123searchresults"></div>').css('max-width', '95%').appendTo(div)
  1296. results.forEach(function (html) {
  1297. const singleresult = $('<div class="result"></div>').html(fixMetacriticURLs(html) + '<div style="clear:left"></div>').appendTo(resultdiv)
  1298. $('<span title="Assist us: This is the correct entry!" style="cursor:pointer; color:green; font-size: 13px;">&check;</span>').prependTo(singleresult).click(accept)
  1299. })
  1300. resultdiv.find('.metascore_w.album').removeClass('album') // Remove some classes
  1301. resultdiv.find('.must-see').remove() // Remove some elements
  1302.  
  1303. const sub = $('#mcdiv123 .sub').length ? $('#mcdiv123 .sub').html('') : $('<div class="sub"></div>').appendTo(div)
  1304. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + url + '" title="Open Metacritic">' + decodeURI(url.replace('https://www.', '@')) + '</a>').appendTo(sub)
  1305. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px;">&#10062;</span>').appendTo(sub).click(function () {
  1306. document.body.removeChild(this.parentNode.parentNode)
  1307. })
  1308. $('<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() })
  1309. } else {
  1310. // No results
  1311. loader.remove()
  1312. const resultdiv = $('#mcdiv123searchresults').length ? $('#mcdiv123searchresults').html('') : $('<div id="mcdiv123searchresults"></div>').appendTo(div)
  1313. resultdiv.html('No search results.')
  1314.  
  1315. const sub = $('#mcdiv123 .sub').length ? $('#mcdiv123 .sub').html('') : $('<div class="sub"></div>').appendTo(div)
  1316. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + url + '" title="Open Metacritic">' + decodeURI(url.replace('https://www.', '@')) + '</a>').appendTo(sub)
  1317. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px;">&#10062;</span>').appendTo(sub).click(function () {
  1318. document.body.removeChild(this.parentNode.parentNode)
  1319. })
  1320. }
  1321. }
  1322.  
  1323. function showHoverInfo (response, orgMetaUrl) {
  1324. const html = fixMetacriticURLs(response.responseText)
  1325. const time = new Date(response.time)
  1326. const url = response.finalUrl
  1327.  
  1328. $('#mcdiv123').remove()
  1329. const div = $('<div id="mcdiv123"></div>').appendTo(document.body)
  1330. div.css({
  1331. position: 'fixed',
  1332. bottom: 0,
  1333. left: 0,
  1334. minWidth: 300,
  1335. backgroundColor: '#fff',
  1336. border: '2px solid #bbb',
  1337. borderRadius: ' 6px',
  1338. boxShadow: '0 0 3px 3px rgba(100, 100, 100, 0.2)',
  1339. color: '#000',
  1340. padding: ' 3px',
  1341. zIndex: '2147483601'
  1342. })
  1343.  
  1344. // Functions for communication between page and iframe
  1345. // Mozilla can access parent.document
  1346. // Chrome can use postMessage()
  1347. let frameStatus = false // if this remains false, loading the frame content failed. A reason could be "Content Security Policy"
  1348. function loadExternalImage (url, myframe) {
  1349. // Load external image, bypass CSP
  1350. GM.xmlHttpRequest({
  1351. method: 'GET',
  1352. url,
  1353. responseType: 'arraybuffer',
  1354. onload: function (response) {
  1355. myframe.contentWindow.postMessage({
  1356. mcimessage_imgLoaded: true,
  1357. mcimessage_imgData: response.response,
  1358. mcimessage_imgOrgSrc: url
  1359. }, '*')
  1360. }
  1361. })
  1362. }
  1363. const functions = {
  1364. parent: function () {
  1365. const f = parent.document.getElementById('mciframe123')
  1366. let lastdiff = -200000
  1367. window.addEventListener('message', function (e) {
  1368. if (typeof e.data !== 'object') {
  1369. return
  1370. } else if ('mcimessage0' in e.data) {
  1371. frameStatus = true // Frame content was loaded successfully
  1372. } else if ('mcimessage1' in e.data) {
  1373. f.style.width = parseInt(f.style.width) + 10 + 'px'
  1374. if (e.data.heightdiff === lastdiff) {
  1375. f.style.height = parseInt(f.style.height) + 5 + 'px'
  1376. }
  1377. lastdiff = e.data.heightdiff
  1378. } else if ('mcimessage2' in e.data) {
  1379. f.style.height = parseInt(f.style.height) + 15 + 'px'
  1380. f.style.width = '400px'
  1381. } else if ('mcimessage_loadImg' in e.data) {
  1382. loadExternalImage(e.data.mcimessage_imgUrl, f)
  1383. } else {
  1384. return
  1385. }
  1386. if (f.contentWindow != null) {
  1387. f.contentWindow.postMessage({
  1388. mcimessage3: true,
  1389. mciframe123_clientHeight: f.clientHeight,
  1390. mciframe123_clientWidth: f.clientWidth
  1391. }, '*')
  1392. }
  1393. })
  1394. },
  1395. frame: function () {
  1396. parent.postMessage({ mcimessage0: true }, '*') // Loading frame content was successfull
  1397.  
  1398. let i = 0
  1399. window.addEventListener('message', function (e) {
  1400. if (typeof e.data === 'object' && 'mcimessage_imgLoaded' in e.data) {
  1401. // Load external image
  1402. const arrayBufferView = new Uint8Array(e.data.mcimessage_imgData)
  1403. const blob = new Blob([arrayBufferView], { type: 'image/jpeg' })
  1404. const urlCreator = window.URL || window.webkitURL
  1405. const imageUrl = urlCreator.createObjectURL(blob)
  1406. const img = failedImages[e.data.mcimessage_imgOrgSrc]
  1407. img.src = imageUrl
  1408. }
  1409.  
  1410. if (!('mcimessage3' in e.data)) return
  1411.  
  1412. if (e.data.mciframe123_clientHeight < document.body.scrollHeight && i < 100) {
  1413. parent.postMessage({ mcimessage1: 1, heightdiff: document.body.scrollHeight - e.data.mciframe123_clientHeight }, '*')
  1414. i++
  1415. }
  1416. if (i >= 100) {
  1417. parent.postMessage({ mcimessage2: 1 }, '*')
  1418. i = 0
  1419. }
  1420. })
  1421. parent.postMessage({ mcimessage1: 1, heightdiff: -100000 }, '*')
  1422. }
  1423.  
  1424. }
  1425.  
  1426. const css = `#hover_div .clr { clear: both}
  1427. #hover_div .fl{float: left}
  1428. #hover_div { background-color: #fff; color: #666; font-family:Arial,Helvetica,sans-serif; font-size:12px; font-weight:400; font-style:normal;}
  1429. #hover_div .hoverinfo .hover_left { float: left}
  1430. #hover_div .hoverinfo .product_image_wrapper { color: #999; font-size: 6px; font-weight: normal; min-height: 98px; min-width: 98px;}
  1431. #hover_div .hoverinfo .product_image_wrapper a { color: #999; font-size: 6px; font-weight: normal;}
  1432. #hover_div a * { cursor: pointer}
  1433. #hover_div a { color: #09f; font-weight: bold;}
  1434. #hover_div a:link, #hover_div a:visited { text-decoration: none;}
  1435. #hover_div a:hover { text-decoration: underline;}
  1436. #hover_div .hoverinfo .hover_right { float: left; margin-left: 15px; max-width: 395px;}
  1437. #hover_div .hoverinfo .product_title { color: #333; font-family: georgia,serif; font-size: 24px; line-height: 26px; margin-bottom: 10px;}
  1438. #hover_div .hoverinfo .product_title a { color:#333; font-family: georgia,serif; font-size: 24px;}
  1439. #hover_div .hoverinfo .summary_detail.publisher, .hoverinfo .summary_detail.release_data { float: left}
  1440. #hover_div .hoverinfo .summary_detail { font-size: 11px; margin-bottom: 10px;}
  1441. #hover_div .hoverinfo .summary_detail.product_credits a { color: #999; font-weight: normal; }
  1442. #hover_div .hoverinfo .hr { background-color: #ccc; height: 2px; margin: 15px 0 10px;}
  1443. #hover_div .hoverinfo .hover_scores { width: 100%; border-collapse: collapse; border-spacing: 0;}
  1444. #hover_div .hoverinfo .hover_scores td.num { width: 39px}
  1445. #hover_div .hoverinfo .hover_scores td { vertical-align: middle}
  1446. #hover_div caption, #hover_div th, #hover_div td { font-weight: normal; text-align: left;}
  1447. #hover_div .metascore_anchor, #hover_div a.metascore_w { text-decoration: none !important}
  1448. #hover_div span.metascore_w, #hover_div a.metascore_w { display: inline-block; padding:0px;}
  1449. .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;}
  1450. #hover_div .metascore, #hover_div .metascore a, #hover_div .avguserscore, #hover_div .avguserscore a { color: #fff}
  1451. #hover_div .critscore, #hover_div .critscore a, #hover_div .userscore, #hover_div .userscore a { color: #333}
  1452. .score_tbd { background: #eaeaea; color: #333; font-size: 14px;}
  1453. #hover_div .score_tbd a { color: #333}
  1454. #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}
  1455. #hover_div.mixed, .neutral,#hover_div .score_mixed,#hover_div .carousel_set a.product_mixed:hover { background-color: #fc3; color: #333;}
  1456. #hover_div .score_mixed a { color: #333}
  1457. #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}
  1458. .critscore_terrible, .critscore_unfavorable { border-color: #f00}
  1459. .critscore_mixed { border-color: #fc3}
  1460. .critscore_favorable, .critscore_outstanding { border-color: #6c3}
  1461. .metascore .score_total, .userscore .score_total { display: none; visibility: hidden;}
  1462. .hoverinfo .metascore_label, .hoverinfo .userscore_label { font-size: 12px; font-weight: bold; line-height: 16px; margin-top: 2%;}
  1463. .hoverinfo .metascore_review_count, .hoverinfo .userscore_review_count { font-size: 11px}
  1464. .hoverinfo .hover_scores td { vertical-align: middle}
  1465. .hoverinfo .hover_scores td.num { width: 39px}
  1466. .hoverinfo .hover_scores td.usr.num { padding-left: 20px}
  1467. .metascore_anchor, a.metascore_w { text-decoration: none !important}
  1468. .metascore_w.album { padding-top:0px; !important}
  1469. .metascore_w.user { border-radius: 55%; color: #fff;}
  1470. .metascore_anchor, .metascore_w.album { padding: 0px;!important, padding-top: 0px;!important}
  1471. a.metascore_w { text-decoration: none!important}
  1472. .metascore_anchor:hover { text-decoration: none!important}
  1473. .metascore_w:hover { text-decoration: none!important}
  1474. span.metascore_w, a.metascore_w { display: inline-block}
  1475. .metascore_w.xlarge, .metascore_w.xl { font-size: 42px}
  1476. .metascore_w.large, .metascore_w.lrg { font-size: 25px}
  1477. .m .metascore_w.medium, .m .metascore_w.med { font-size: 19px}
  1478. .metascore_w.med_small { font-size: 14px}
  1479. .metascore_w.small, .metascore_w.sm { font-size: 12px}
  1480. .metascore_w.tiny { height: 1.9em; font-size: 11px; line-height: 1.9em;}
  1481. .metascore_w.user { border-radius: 55%; color: #fff;}
  1482. .metascore_w.user.small, .metascore_w.user.sm { font-size: 11px}
  1483. .metascore_w.tbd, .metascore_w.score_tbd { color: #000!important; background-color: #ccc;}
  1484. .metascore_w.tbd.hide_tbd, .metascore_w.score_tbd.hide_tbd { visibility: hidden}
  1485. .metascore_w.tbd.no_tbd, .metascore_w.score_tbd.no_tbd { display: none}
  1486. .metascore_w.noscore::before, .metascore_w.score_noscore::before { content: '\u2022\u2022\u2022'}
  1487. .metascore_w.noscore, .metascore_w.score_noscore { color: #fff!important; background-color: #ccc;}
  1488. .metascore_w.rip, .metascore_w.score_rip { border-radius: 4px; color: #fff!important; background-color: #999;}
  1489. .metascore_w.negative, .metascore_w.score_terrible, .metascore_w.score_unfavorable { background-color: #f00}
  1490. .metascore_w.mixed, .metascore_w.forty, .metascore_w.game.fifty, .metascore_w.score_mixed { background-color: #fc3}
  1491. .metascore_w.positive, .metascore_w.sixtyone, .metascore_w.game.seventyfive, .metascore_w.score_favorable, .metascore_w.score_outstanding { background-color: #6c3}
  1492. .metascore_w.indiv { height: 1.9em; width: 1.9em; font-size: 15px; line-height: 1.9em;}
  1493. .metascore_w.indiv.large, .metascore_w.indiv.lrg { font-size: 24px}
  1494. .m .metascore_w.indiv.medium, .m .metascore_w.indiv.med { font-size: 16px}
  1495. .metascore_w.indiv.small, .metascore_w.indiv.sm { font-size: 11px}
  1496. .metascore_w.indiv.perfect { padding-right: 1px}
  1497. .hover_esite { display:none; }
  1498. .promo_amazon .esite_btn { margin: 3px 0 0 7px;}
  1499. .esite_amazon { background-color: #fdc354; border: 1px solid #aaa;}
  1500. .esite_label_wrapper { display:none;}
  1501. .esite_btn { border-radius: 4px; color: #222; font-size: 12px; height: 40px; line-height: 40px; width: 120px;}
  1502. .chart{background-color:inherit!important;margin-top:-3px}
  1503. .chart_bg{width:100%;border-top:3px solid rgba(150,150,150,0.3)}
  1504. .chart .bar{width:100%;height:3px}
  1505. .chart .count{font-size:10px}`
  1506.  
  1507. let framesrc = 'data:text/html,'
  1508. framesrc += encodeURIComponent(`<!DOCTYPE html>
  1509. <html lang="en">
  1510. <head>
  1511. <meta charset="utf-8">
  1512. <title>Metacritic info</title>
  1513. <style>body { margin:0px; padding:0px; background:white; }${css}
  1514. </style>
  1515. <script>
  1516. const failedImages = {};
  1517. function detectCSP(img) {
  1518. if(img.complete && (!img.naturalWidth || !img.naturalHeight)) {
  1519. return true;
  1520. }
  1521. return false;
  1522. }
  1523. function findCSPerrors() {
  1524. const imgs = document.querySelectorAll("img");
  1525. for(let i = 0; i < imgs.length; i++) {
  1526. if(imgs[i].complete && detectCSP(imgs[i])) {
  1527. fixCSP(imgs[i]);
  1528. }
  1529. }
  1530. }
  1531. function fixCSP(img) {
  1532. console.debug("ShowMetacriticRatings(iFrame): Loading image failed. Bypassing CSP...");
  1533. failedImages[img.src] = img;
  1534. parent.postMessage({"mcimessage_loadImg":true, "mcimessage_imgUrl": img.src},"*");
  1535. }
  1536. function on_load() {
  1537. (${functions.frame.toString()})();
  1538. window.setTimeout(findCSPerrors, 500);
  1539. }
  1540. </script>
  1541. </head>
  1542. <body onload="on_load();">
  1543. <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">
  1544. <div class="hover_content">${html}</div>
  1545. </div>
  1546. </body>
  1547. </html>`)
  1548.  
  1549. const frame = $('<iframe></iframe>').appendTo(div)
  1550. frame.attr('id', 'mciframe123')
  1551. frame.attr('src', framesrc)
  1552. frame.attr('scrolling', 'auto')
  1553. frame.css({
  1554. width: 380,
  1555. height: 150,
  1556. border: 'none'
  1557. })
  1558.  
  1559. window.setTimeout(function () {
  1560. if (!frameStatus) { // Loading frame content failed.
  1561. // Directly inject the html without an iframe (this may break the site or the metacritic)
  1562. console.debug('ShowMetacriticRatings: Loading iframe content failed. Injecting directly.')
  1563. $('head').append(`<style>${css}</style>`)
  1564. 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">
  1565. <div class="hover_content">${html}</div>
  1566. </div>`)
  1567. frame.replaceWith(noframe)
  1568. }
  1569. }, 2000)
  1570.  
  1571. functions.parent()
  1572.  
  1573. const sub = $('<div></div>').appendTo(div)
  1574. $('<time style="color:#b6b6b6; font-size: 11px;" datetime="' + time + '" title="' + time.toLocaleTimeString() + ' ' + time.toLocaleDateString() + '">' + minutesSince(time) + '</time>').appendTo(sub)
  1575. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="' + url + '" title="Open Metacritic">' + decodeURI(url.replace('https://www.', '@')) + '</a>').appendTo(sub)
  1576. $('<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 () {
  1577. const metaurl = $(this).data('url')
  1578. addToTemporaryBlacklist(metaurl)
  1579. document.body.removeChild(this.parentNode.parentNode)
  1580. })
  1581.  
  1582. $('<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 () {
  1583. const docurl = document.location.href
  1584. const metaurl = $(this).data('url')
  1585. addToMap(docurl, metaurl).then(function (r) {
  1586. balloonAlert('Thanks for your submission!\n\nSaved as a correct entry.\n\n' + r[0] + '\n' + r[1], 6000, 'Success')
  1587. })
  1588. })
  1589. $('<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 () {
  1590. if (!confirm('This is NOT the correct entry!\n\nAdd to blacklist?')) return
  1591. const docurl = document.location.href
  1592. const metaurl = $(this).data('url')
  1593. addToBlacklist(docurl, metaurl).then(function (r) {
  1594. balloonAlert('Thanks for your submission!\n\nSaved to blacklist.\n\n' + r[0] + '\n' + r[1], 6000, 'Success')
  1595. })
  1596.  
  1597. openSearchBox(true)
  1598. })
  1599.  
  1600. // Store response in cache:
  1601. if (!('cached' in response)) {
  1602. storeInHoverCache(current.metaurl, response, orgMetaUrl)
  1603. }
  1604. }
  1605.  
  1606. function metacriticGeneralProductSetup () {
  1607. current.broadenCounter = 0
  1608. }
  1609.  
  1610. const metacritic = {
  1611. mapped: function metacriticMapped (docurl, product, metaurl, type) {
  1612. // url was in the map/whitelist
  1613. current.data = []
  1614. current.docurl = docurl
  1615. current.product = product
  1616. current.metaurl = metaurl
  1617. current.type = type
  1618. current.searchTerm = null
  1619. loadMetacriticUrl()
  1620. },
  1621. music: function metacriticMusic (docurl, product, artistname, albumname) {
  1622. current.data = [albumname.trim(), artistname.trim()]
  1623. artistname = name2metacritic(artistname)
  1624. albumname = albumname.replace('&', ' ')
  1625. albumname = name2metacritic(albumname)
  1626. current.docurl = docurl
  1627. current.product = product
  1628. current.metaurl = baseURLmusic + albumname + '/' + artistname
  1629. current.type = 'music'
  1630. current.searchTerm = albumname + '/' + artistname
  1631. loadMetacriticUrl()
  1632. },
  1633. movie: function metacriticMovie (docurl, product, moviename) {
  1634. current.data = [moviename.trim()]
  1635. moviename = name2metacritic(moviename)
  1636. current.docurl = docurl
  1637. current.product = product
  1638. current.metaurl = baseURLmovie + moviename
  1639. current.type = 'movie'
  1640. current.searchTerm = moviename
  1641. loadMetacriticUrl()
  1642. },
  1643. tv: function metacriticTv (docurl, product, seriesname) {
  1644. current.data = [seriesname.trim()]
  1645. seriesname = name2metacritic(seriesname)
  1646. current.docurl = docurl
  1647. current.product = product
  1648. current.metaurl = baseURLtv + seriesname
  1649. current.type = 'tv'
  1650. current.searchTerm = seriesname
  1651. loadMetacriticUrl()
  1652. },
  1653. pcgame: function metacriticPcgame (docurl, product, gamename) {
  1654. current.data = [gamename.trim()]
  1655. gamename = name2metacritic(gamename)
  1656. current.docurl = docurl
  1657. current.product = product
  1658. current.metaurl = baseURLpcgame + gamename
  1659. current.type = 'pcgame'
  1660. current.searchTerm = gamename
  1661. loadMetacriticUrl()
  1662. },
  1663. ps4game: function metacriticPs4game (docurl, product, gamename) {
  1664. current.data = [gamename.trim()]
  1665. gamename = name2metacritic(gamename)
  1666. current.docurl = docurl
  1667. current.product = product
  1668. current.metaurl = baseURLps4 + gamename
  1669. current.type = 'ps4game'
  1670. current.searchTerm = gamename
  1671. loadMetacriticUrl()
  1672. },
  1673. xonegame: function metacriticXonegame (docurl, product, gamename) {
  1674. current.data = [gamename.trim()]
  1675. gamename = name2metacritic(gamename)
  1676. current.docurl = docurl
  1677. current.product = product
  1678. current.metaurl = baseURLxone + gamename
  1679. current.type = 'xonegame'
  1680. current.searchTerm = gamename
  1681. loadMetacriticUrl()
  1682. }
  1683. }
  1684.  
  1685. const Always = () => true
  1686. const sites = {
  1687. bandcamp: {
  1688. host: ['bandcamp.com'],
  1689. condition: () => unsafeWindow && unsafeWindow.TralbumData && unsafeWindow.TralbumData.current,
  1690. products: [{
  1691. condition: Always,
  1692. type: 'music',
  1693. data: () => [unsafeWindow.TralbumData.artist, unsafeWindow.TralbumData.current.title]
  1694. }]
  1695. },
  1696. itunes: {
  1697. host: ['itunes.apple.com'],
  1698. condition: Always,
  1699. products: [{
  1700. condition: () => ~document.location.href.indexOf('/movie/'),
  1701. type: 'movie',
  1702. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  1703. },
  1704. {
  1705. condition: () => ~document.location.href.indexOf('/tv-season/'),
  1706. type: 'tv',
  1707. data: function () {
  1708. let name = parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  1709. if (~name.indexOf(', Season')) {
  1710. name = name.split(', Season')[0]
  1711. }
  1712. return name
  1713. }
  1714. },
  1715. {
  1716. condition: () => ~document.location.href.indexOf('/album/'),
  1717. type: 'music',
  1718. data: function () {
  1719. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  1720. const album = ld[0]
  1721. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  1722. return [artist, album]
  1723. }
  1724. }]
  1725. },
  1726. 'music.apple': {
  1727. host: ['music.apple.com'],
  1728. condition: Always,
  1729. products: [{
  1730. condition: () => ~document.location.href.indexOf('/album/') && parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum')).length > 1,
  1731. type: 'music',
  1732. data: function () {
  1733. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  1734. const album = ld[0]
  1735. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  1736. return [artist, album]
  1737. }
  1738. }]
  1739. },
  1740. googleplay: {
  1741. host: ['play.google.com'],
  1742. condition: Always,
  1743. products: [
  1744. {
  1745. condition: () => ~document.location.href.indexOf('/album/'),
  1746. type: 'music',
  1747. data: () => [document.querySelector('[itemprop="byArtist"] meta[itemprop="name"]').content, document.querySelector('[itemtype="https://schema.org/MusicAlbum"] meta[itemprop="name"]').content]
  1748. },
  1749. {
  1750. condition: () => ~document.location.href.indexOf('/movies/details/'),
  1751. type: 'movie',
  1752. data: () => document.querySelector('*[itemprop=name]').textContent
  1753. }
  1754. ]
  1755. },
  1756. imdb: {
  1757. host: ['imdb.com'],
  1758. condition: () => !~document.location.pathname.indexOf('/mediaviewer') && !~document.location.pathname.indexOf('/mediaindex') && !~document.location.pathname.indexOf('/videoplayer'),
  1759. products: [
  1760. {
  1761. condition: function () {
  1762. const e = document.querySelector("meta[property='og:type']")
  1763. if (e && e.content === 'video.movie') {
  1764. return true
  1765. } else if (document.querySelector('[data-testid="hero-title-block__title"]') && !document.querySelector('[data-testid="hero-subnav-bar-left-block"] a[href*="episodes/"]')) {
  1766. // New design 2020-12
  1767. return true
  1768. }
  1769. return false
  1770. },
  1771. type: 'movie',
  1772. data: function () {
  1773. if (document.querySelector('[data-testid="hero-title-block__title"]')) {
  1774. // New design 2020-12
  1775. return document.querySelector('[data-testid="hero-title-block__title"]').textContent
  1776. } 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
  1777. let name = document.querySelector("meta[property='og:title']").content.trim()
  1778. if (name.indexOf('- IMDb') !== -1) {
  1779. name = name.replace('- IMDb', '').trim()
  1780. }
  1781. name = name.replace(/\(\d{4}\)/, '').trim()
  1782. return name
  1783. } else if (document.querySelector('.originalTitle') && document.querySelector('.title_wrapper h1')) { // Use English title 2018
  1784. return document.querySelector('.title_wrapper h1').firstChild.textContent.trim()
  1785. } else if (document.querySelector('script[type="application/ld+json"]')) { // Use original language title
  1786. return parseLDJSON('name')
  1787. } else if (document.querySelector('h1[itemprop=name]')) { // Movie homepage (New design 2015-12)
  1788. return document.querySelector('h1[itemprop=name]').firstChild.textContent.trim()
  1789. } else if (document.querySelector('*[itemprop=name] a') && document.querySelector('*[itemprop=name] a').firstChild.textContent) { // Subpage of a move
  1790. return document.querySelector('*[itemprop=name] a').firstChild.textContent.trim()
  1791. } else if (document.querySelector('.title-extra[itemprop=name]')) { // Movie homepage: sub-/alternative-/original title
  1792. return document.querySelector('.title-extra[itemprop=name]').firstChild.textContent.replace(/"/g, '').trim()
  1793. } else if (document.querySelector('*[itemprop=name]')) { // Movie homepage (old design)
  1794. return document.querySelector('*[itemprop=name]').firstChild.textContent.trim()
  1795. } else {
  1796. return document.title.match(/(.+?)\s+(\(\d+\))? - IMDb/)[1]
  1797. }
  1798. }
  1799. },
  1800. {
  1801. condition: function () {
  1802. const e = document.querySelector("meta[property='og:type']")
  1803. if (e && e.content === 'video.tv_show') {
  1804. return true
  1805. } else if (document.querySelector('[data-testid="hero-subnav-bar-left-block"] a[href*="episodes/"]')) {
  1806. // New design 2020-12
  1807. return true
  1808. }
  1809. return false
  1810. },
  1811. type: 'tv',
  1812. data: function () {
  1813. if (document.querySelector('[data-testid="hero-title-block__title"]')) {
  1814. // New design 2020-12
  1815. return document.querySelector('[data-testid="hero-title-block__title"]').textContent
  1816. } else if (document.querySelector('*[itemprop=name]')) {
  1817. return document.querySelector('*[itemprop=name]').textContent
  1818. } else if (document.querySelector('script[type="application/ld+json"]')) {
  1819. const jsonld = JSON.parse(document.querySelector('script[type="application/ld+json"]').innerText)
  1820. return jsonld.name
  1821. } else {
  1822. return document.title.match(/(.+?)\s+\(TV/)[1]
  1823. }
  1824. }
  1825. }
  1826. ]
  1827. },
  1828. steam: {
  1829. host: ['store.steampowered.com'],
  1830. condition: () => document.querySelector('*[itemprop=name]'),
  1831. products: [{
  1832. condition: Always,
  1833. type: 'pcgame',
  1834. data: () => document.querySelector('*[itemprop=name]').textContent
  1835. }]
  1836. },
  1837. rottentomatoes: {
  1838. host: ['rottentomatoes.com'],
  1839. condition: Always,
  1840. products: [{
  1841. condition: () => document.location.pathname.startsWith('/m/'),
  1842. type: 'movie',
  1843. data: () => document.querySelector('h1').firstChild.textContent
  1844. },
  1845. {
  1846. condition: () => document.location.pathname.startsWith('/tv/'),
  1847. type: 'tv',
  1848. data: () => unsafeWindow.BK.TvSeriesTitle
  1849. }
  1850. ]
  1851. },
  1852. serienjunkies: {
  1853. host: ['www.serienjunkies.de'],
  1854. condition: Always,
  1855. products: [{
  1856. condition: () => Always,
  1857. type: 'tv',
  1858. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  1859. }]
  1860. },
  1861. gamespot: {
  1862. host: ['gamespot.com'],
  1863. condition: () => document.querySelector('[itemprop=device]'),
  1864. products: [
  1865. {
  1866. condition: () => ~$('[itemprop=device]').text().indexOf('PC'),
  1867. type: 'pcgame',
  1868. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  1869. },
  1870. {
  1871. condition: () => ~$('[itemprop=device]').text().indexOf('PS4'),
  1872. type: 'ps4game',
  1873. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  1874. },
  1875. {
  1876. condition: () => ~$('[itemprop=device]').text().indexOf('XONE'),
  1877. type: 'xonegame',
  1878. data: () => parseLDJSON('name', (j) => (j['@type'] === 'VideoGame'))
  1879. }
  1880. ]
  1881. },
  1882. amazon: {
  1883. host: ['amazon.'],
  1884. condition: Always,
  1885. products: [
  1886. {
  1887. condition: () => document.location.hostname === 'music.amazon.com' && document.location.pathname.startsWith('/albums/') && document.querySelector('.viewTitle'), // "Amazon Music Unlimited" page
  1888. type: 'music',
  1889. data: function () {
  1890. const artist = document.querySelector('.artistLink').textContent.trim()
  1891. let title = document.querySelector('.viewTitle').textContent.trim()
  1892. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  1893. if (artist && title) {
  1894. return [artist, title]
  1895. }
  1896. return false
  1897. }
  1898. },
  1899. {
  1900. condition: function () { // "Normal amazon" page
  1901. try {
  1902. if (document.querySelector('.nav-categ-image').alt.toLowerCase().indexOf('musi') !== -1) {
  1903. return true
  1904. }
  1905. } catch (e) {}
  1906. const music = ['Music', 'Musique', 'Musik', 'Música', 'Musica', '音楽']
  1907. return music.some(function (s) {
  1908. if (~document.title.indexOf(s)) {
  1909. return true
  1910. } else {
  1911. return false
  1912. }
  1913. })
  1914. },
  1915. type: 'music',
  1916. data: function () {
  1917. let artist = false
  1918. let title = false
  1919. if (document.querySelector('#ProductInfoArtistLink')) {
  1920. artist = document.querySelector('#ProductInfoArtistLink').textContent.trim()
  1921. } else if (document.querySelector('#bylineInfo .author>*')) {
  1922. artist = document.querySelector('#bylineInfo .author>*').textContent.trim()
  1923. }
  1924.  
  1925. if (document.querySelector('#dmusicProductTitle_feature_div')) {
  1926. title = document.querySelector('#dmusicProductTitle_feature_div').textContent.trim()
  1927. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  1928. } else if (document.querySelector('#productTitle')) {
  1929. title = document.querySelector('#productTitle').textContent.trim()
  1930. title = title.replace(/\[([^\]]*)\]/g, '').trim() // Remove [brackets] and their content
  1931. }
  1932. return [artist, title]
  1933. }
  1934. },
  1935. {
  1936. condition: () => (document.querySelector('[data-automation-id=title]') && (
  1937. document.getElementsByClassName('av-season-single').length ||
  1938. document.querySelector('[data-automation-id="num-of-seasons-badge"]') ||
  1939. document.getElementById('tab-selector-episodes') ||
  1940. document.getElementById('av-droplist-av-atf-season-selector')
  1941. )),
  1942. type: 'tv',
  1943. data: () => document.querySelector('[data-automation-id=title]').textContent.trim()
  1944. },
  1945. {
  1946. condition: () => ((
  1947. document.getElementsByClassName('av-season-single').length ||
  1948. document.querySelector('[data-automation-id="num-of-seasons-badge"]') ||
  1949. document.getElementById('tab-selector-episodes') ||
  1950. document.getElementById('av-droplist-av-atf-season-selector')
  1951. ) && Array.from(document.querySelectorAll('script[type="text/template"]')).map(e => e.innerHTML.match(/parentTitle"\s*:\s*"(.+?)"/)).some((x) => x != null)),
  1952. type: 'tv',
  1953. data: () => Array.from(document.querySelectorAll('script[type="text/template"]')).map(e => e.innerHTML.match(/parentTitle"\s*:\s*"(.+?)"/)).filter((x) => x != null)[0][1]
  1954. },
  1955. {
  1956. condition: () => document.querySelector('[data-automation-id=title]'),
  1957. type: 'movie',
  1958. data: () => document.querySelector('[data-automation-id=title]').textContent.trim().replace(/\[.{1,8}\]/, '')
  1959. }
  1960. ]
  1961. },
  1962. BoxOfficeMojo: {
  1963. host: ['boxofficemojo.com'],
  1964. condition: () => Always,
  1965. products: [
  1966. {
  1967. condition: () => document.location.pathname.startsWith('/release/'),
  1968. type: 'movie',
  1969. data: () => document.querySelector('meta[name=title]').content
  1970. },
  1971. {
  1972. // Old page design
  1973. condition: () => ~document.location.search.indexOf('id=') && document.querySelector('#body table:nth-child(2) tr:first-child b'),
  1974. type: 'movie',
  1975. data: () => document.querySelector('#body table:nth-child(2) tr:first-child b').firstChild.textContent
  1976. }]
  1977. },
  1978. AllMovie: {
  1979. host: ['allmovie.com'],
  1980. condition: () => document.querySelector('h2.movie-title'),
  1981. products: [{
  1982. condition: () => document.querySelector('h2.movie-title'),
  1983. type: 'movie',
  1984. data: () => document.querySelector('h2.movie-title').firstChild.textContent.trim()
  1985. }]
  1986. },
  1987. 'en.wikipedia': {
  1988. host: ['en.wikipedia.org'],
  1989. condition: Always,
  1990. products: [{
  1991. condition: function () {
  1992. if (!document.querySelector('.infobox .summary')) {
  1993. return false
  1994. }
  1995. const r = /\d\d\d\d films/
  1996. return $('#catlinks a').filter((i, e) => e.firstChild.textContent.match(r)).length
  1997. },
  1998. type: 'movie',
  1999. data: () => document.querySelector('.infobox .summary').firstChild.textContent
  2000. },
  2001. {
  2002. condition: function () {
  2003. if (!document.querySelector('.infobox .summary')) {
  2004. return false
  2005. }
  2006. const r = /television series/
  2007. return $('#catlinks a').filter((i, e) => e.firstChild.textContent.match(r)).length
  2008. },
  2009. type: 'tv',
  2010. data: () => document.querySelector('.infobox .summary').firstChild.textContent
  2011. }]
  2012. },
  2013. fandango: {
  2014. host: ['fandango.com'],
  2015. condition: () => document.querySelector("meta[property='og:title']"),
  2016. products: [{
  2017. condition: Always,
  2018. type: 'movie',
  2019. data: () => document.querySelector("meta[property='og:title']").content.match(/(.+?)\s+\(\d{4}\)/)[1].trim()
  2020. }]
  2021. },
  2022. flixster: {
  2023. host: ['www.flixster.com'],
  2024. condition: () => Always,
  2025. products: [{
  2026. condition: () => parseLDJSON('@type') === 'Movie',
  2027. type: 'movie',
  2028. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2029. }]
  2030. },
  2031. themoviedb: {
  2032. host: ['themoviedb.org'],
  2033. condition: () => document.querySelector("meta[property='og:type']"),
  2034. products: [{
  2035. condition: () => document.querySelector("meta[property='og:type']").content === 'movie',
  2036. type: 'movie',
  2037. data: () => document.querySelector("meta[property='og:title']").content
  2038. },
  2039. {
  2040. condition: () => document.querySelector("meta[property='og:type']").content === 'tv' || document.querySelector("meta[property='og:type']").content === 'tv_series',
  2041. type: 'tv',
  2042. data: () => document.querySelector("meta[property='og:title']").content
  2043. }]
  2044. },
  2045. letterboxd: {
  2046. host: ['letterboxd.com'],
  2047. condition: () => unsafeWindow.filmData && 'name' in unsafeWindow.filmData,
  2048. products: [{
  2049. condition: Always,
  2050. type: 'movie',
  2051. data: () => unsafeWindow.filmData.name
  2052. }]
  2053. },
  2054. TVmaze: {
  2055. host: ['tvmaze.com'],
  2056. condition: () => document.querySelector('h1'),
  2057. products: [{
  2058. condition: Always,
  2059. type: 'tv',
  2060. data: () => document.querySelector('h1').firstChild.textContent
  2061. }]
  2062. },
  2063. TVGuide: {
  2064. host: ['tvguide.com'],
  2065. condition: Always,
  2066. products: [{
  2067. condition: () => document.location.pathname.startsWith('/tvshows/'),
  2068. type: 'tv',
  2069. data: function () {
  2070. if (document.querySelector('meta[itemprop=name]')) {
  2071. return document.querySelector('meta[itemprop=name]').content
  2072. } else {
  2073. return document.querySelector("meta[property='og:title']").content.split('|')[0]
  2074. }
  2075. }
  2076. }]
  2077. },
  2078. followshows: {
  2079. host: ['followshows.com'],
  2080. condition: Always,
  2081. products: [{
  2082. condition: () => document.querySelector("meta[property='og:type']").content === 'video.tv_show',
  2083. type: 'tv',
  2084. data: () => document.querySelector("meta[property='og:title']").content
  2085. }]
  2086. },
  2087. TheTVDB: {
  2088. host: ['thetvdb.com'],
  2089. condition: Always,
  2090. products: [{
  2091. condition: () => document.location.pathname.startsWith('/series/'),
  2092. type: 'tv',
  2093. data: () => document.getElementById('series_title').firstChild.textContent.trim()
  2094. },
  2095. {
  2096. condition: () => document.location.pathname.startsWith('/movies/'),
  2097. type: 'movie',
  2098. data: () => document.getElementById('series_title').firstChild.textContent.trim()
  2099. }]
  2100. },
  2101. ConsequenceOfSound: {
  2102. host: ['consequence.net', 'consequenceofsound.net'],
  2103. condition: () => document.querySelector('#main-content .review-summary'),
  2104. products: [
  2105. {
  2106. condition: () => document.querySelector('meta[name="cXenseParse:cns-artist-names"]') && document.querySelector('em'),
  2107. type: 'music',
  2108. data: function () {
  2109. window.setInterval(function () {
  2110. if (document.getElementById('ot-sdk-btn-floating')) {
  2111. document.getElementById('ot-sdk-btn-floating').remove()
  2112. }
  2113. }, 5000)
  2114. const artist = document.querySelector('meta[name="cXenseParse:cns-artist-names"]').content
  2115. const arr = Array.from(document.querySelectorAll('em')).map((em) => em.textContent.trim())
  2116. const counts = {}
  2117. for (const num of arr) {
  2118. counts[num] = counts[num] ? counts[num] + 1 : 1
  2119. }
  2120. const max = Math.max(...Object.values(counts))
  2121. const maxIndex = Object.values(counts).indexOf(max)
  2122. const title = Object.keys(counts)[maxIndex]
  2123. return [artist, title]
  2124. }
  2125. },
  2126. {
  2127. condition: () => document.title.match(/'(.*?)'\s*Album/i) && document.querySelector('meta[name="cXenseParse:cns-artist-names"]'),
  2128. type: 'music',
  2129. data: function () {
  2130. window.setInterval(function () {
  2131. if (document.getElementById('ot-sdk-btn-floating')) {
  2132. document.getElementById('ot-sdk-btn-floating').remove()
  2133. }
  2134. }, 5000)
  2135. const title = document.title.match(/'(.*?)'\s*Album/i)[1]
  2136. const artist = document.querySelector('meta[name="cXenseParse:cns-artist-names"]').content
  2137. return [artist, title]
  2138. }
  2139. },
  2140. {
  2141. condition: () => document.title.match(/(.+?)\s+\u2013\s+(.+?) \| Album Review/),
  2142. type: 'music',
  2143. data: function () {
  2144. window.setInterval(function () {
  2145. if (document.getElementById('ot-sdk-btn-floating')) {
  2146. document.getElementById('ot-sdk-btn-floating').remove()
  2147. }
  2148. }, 5000)
  2149. const m = document.title.match(/(.+?)\s+\u2013\s+(.+?) \| Album Review/)
  2150. return [m[1], m[2]]
  2151. }
  2152. },
  2153. {
  2154. condition: () => document.location.pathname.indexOf('/album-review') !== -1 && document.querySelector('a.tag[href*="/artist/"'),
  2155. type: 'music',
  2156. data: function () {
  2157. window.setInterval(function () {
  2158. if (document.getElementById('ot-sdk-btn-floating')) {
  2159. document.getElementById('ot-sdk-btn-floating').remove()
  2160. }
  2161. }, 5000)
  2162. const artistAndTitleWithDash = document.location.pathname.match(/album-review-([\w-]+)/)[1]
  2163. const artistWithDash = document.querySelector('a.tag[href*="/artist/"').pathname.match(/artist\/([\w-]+)/)[1]
  2164. const titleWithDash = artistAndTitleWithDash.replace(artistWithDash, '')
  2165. const title = titleWithDash.replace('-', ' ').trim()
  2166. const artist = artistWithDash.replace('-', ' ').trim()
  2167. return [artist, title]
  2168. }
  2169. }]
  2170. },
  2171. Pitchfork: {
  2172. host: ['pitchfork.com'],
  2173. condition: () => ~document.location.href.indexOf('/reviews/albums/'),
  2174. products: [{
  2175. condition: () => document.querySelector('.single-album-tombstone'),
  2176. type: 'music',
  2177. data: function () {
  2178. let artist
  2179. let album
  2180. if (document.querySelector('.single-album-tombstone .artists')) {
  2181. artist = document.querySelector('.single-album-tombstone .artists').innerText.trim()
  2182. } else if (document.querySelector('.single-album-tombstone .artist-list')) {
  2183. artist = document.querySelector('.single-album-tombstone .artist-list').innerText.trim()
  2184. }
  2185. if (document.querySelector('.single-album-tombstone h1.review-title')) {
  2186. album = document.querySelector('.single-album-tombstone h1.review-title').innerText.trim()
  2187. } else if (document.querySelector('.single-album-tombstone h1')) {
  2188. album = document.querySelector('.single-album-tombstone h1').innerText.trim()
  2189. }
  2190.  
  2191. return [artist, album]
  2192. }
  2193. }]
  2194. },
  2195. 'Last.fm': {
  2196. host: ['last.fm'],
  2197. condition: () => document.querySelector('*[data-page-resource-type]') && document.querySelector('*[data-page-resource-type]').dataset.pageResourceType === 'album',
  2198. products: [{
  2199. condition: () => document.querySelector('*[data-page-resource-type]').dataset.pageResourceName,
  2200. type: 'music',
  2201. data: function () {
  2202. const artist = document.querySelector('*[data-page-resource-type]').dataset.pageResourceArtistName
  2203. const album = document.querySelector('*[data-page-resource-type]').dataset.pageResourceName
  2204. return [artist, album]
  2205. }
  2206. }]
  2207. },
  2208. TVNfo: {
  2209. host: ['tvnfo.com'],
  2210. condition: () => document.querySelector('.ui.breadcrumb a[href*="/series"]'),
  2211. products: [{
  2212. condition: Always,
  2213. type: 'tv',
  2214. data: function () {
  2215. const years = document.querySelector('#title h1 .years').textContent.trim()
  2216. const title = document.querySelector('#title h1').textContent.replace(years, '').trim()
  2217. return title
  2218. }
  2219. }]
  2220. },
  2221. rateyourmusic: {
  2222. host: ['rateyourmusic.com'],
  2223. condition: () => document.querySelector("meta[property='og:type']"),
  2224. products: [{
  2225. condition: () => document.querySelector("meta[property='og:type']").content === 'music.album',
  2226. type: 'music',
  2227. data: function () {
  2228. const artist = document.querySelector('.section_main_info .artist').innerText.trim()
  2229. const album = document.querySelector('.section_main_info .album_title').innerText.trim()
  2230. return [artist, album]
  2231. }
  2232. }]
  2233. },
  2234. spotify: {
  2235. host: ['open.spotify.com'],
  2236. condition: Always,
  2237. products: [{
  2238. condition: () => document.location.pathname.startsWith('/album/') && document.querySelector('.Root__main-view h1'),
  2239. type: 'music',
  2240. data: function () {
  2241. const album = document.querySelector('.Root__main-view h1').textContent.trim()
  2242. let artist = []
  2243. document.querySelector('.Root__main-view h1').parentNode.parentNode.parentNode.querySelectorAll('a[href*="/artist/"]').forEach(function (a) {
  2244. artist.push(a.textContent.trim())
  2245. })
  2246. artist = artist.join(' ')
  2247. return [artist, album]
  2248. }
  2249. }]
  2250. },
  2251. nme: {
  2252. host: ['nme.com'],
  2253. condition: () => document.location.pathname.startsWith('/reviews/'),
  2254. products: [
  2255. {
  2256. condition: () => document.querySelector('.tdb-breadcrumbs a[href*="/reviews/film-reviews"]'),
  2257. type: 'movie',
  2258. data: function () {
  2259. try {
  2260. return document.title.match(/[‘'](.+?)[’']/)[1]
  2261. } catch (e) {
  2262. try {
  2263. return document.querySelector('h1.tdb-title-text').textContent.match(/[‘'](.+?)[’']/)[1]
  2264. } catch (e) {
  2265. return document.querySelector('h1').textContent.match(/:\s*(.+)/)[1].trim()
  2266. }
  2267. }
  2268. }
  2269. },
  2270. {
  2271. condition: () => document.querySelector('#nme-music-header'),
  2272. type: 'music',
  2273. data: () => document.querySelector('h1.tdb-title-text').textContent.match(/\s*(.+?)\s*.\s*[‘'](.+?)[’']/).slice(1)
  2274. },
  2275. {
  2276. condition: () => document.querySelector('.tdb-breadcrumbs a[href*="/reviews/tv-reviews"]'),
  2277. type: 'tv',
  2278. data: () => document.querySelector('h1.tdb-title-text').textContent.match(/[‘'](.+?)[’']/)[1]
  2279. }]
  2280. },
  2281. albumoftheyear: {
  2282. host: ['albumoftheyear.org'],
  2283. condition: Always,
  2284. products: [{
  2285. condition: () => document.location.pathname.startsWith('/album/'),
  2286. type: 'music',
  2287. data: function () {
  2288. const artist = document.querySelector('*[itemprop=byArtist] *[itemprop=name]').textContent
  2289. const album = document.querySelector('.albumTitle *[itemprop=name]').textContent
  2290. return [artist, album]
  2291. }
  2292. }]
  2293. },
  2294. epguides: {
  2295. host: ['epguides.com'],
  2296. condition: () => document.getElementById('eplist'),
  2297. products: [{
  2298. condition: () => document.getElementById('eplist') && document.querySelector('.center.titleblock h2'),
  2299. type: 'tv',
  2300. data: () => document.querySelector('.center.titleblock h2').textContent.trim()
  2301. }]
  2302. },
  2303. ShareTV: {
  2304. host: ['sharetv.com'],
  2305. condition: () => document.location.pathname.startsWith('/shows/'),
  2306. products: [{
  2307. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:title']"),
  2308. type: 'tv',
  2309. data: () => document.querySelector("meta[property='og:title']").content
  2310. }]
  2311. },
  2312. /*
  2313. netflix: {
  2314. host: ['netflix.com'],
  2315. condition: !(document.querySelector('.button-nfplayerPlay') || document.querySelector('.nf-big-play-pause') || document.querySelector('.AkiraPlayer video')),
  2316.  
  2317. // TODO
  2318. // https://www.netflix.com/de/title/70264888
  2319. // https://www.netflix.com/de/title/70178217
  2320. // https://www.netflix.com/de/title/70305892 ## Movie
  2321. // https://www.netflix.com/de-en/title/80108495 ## No meta
  2322.  
  2323. products: [{
  2324. condition: () => parseLDJSON('@type') === 'Movie',
  2325. type: 'movie',
  2326. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2327. },
  2328. {
  2329. condition: () => parseLDJSON('@type') === 'TVSeries',
  2330. type: 'tv',
  2331. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  2332. }]
  2333. },
  2334. */
  2335. ComedyCentral: {
  2336. host: ['cc.com'],
  2337. condition: () => document.location.pathname.startsWith('/shows/'),
  2338. products: [{
  2339. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:title']"),
  2340. type: 'tv',
  2341. data: () => document.querySelector("meta[property='og:title']").content.replace('| Comedy Central', '').trim()
  2342. },
  2343. {
  2344. condition: () => document.location.pathname.split('/').length === 3 && document.title.match(/(.+?)\s+-\s+Series/),
  2345. type: 'tv',
  2346. data: () => document.title.match(/(.+?)\s+-\s+Series/)[1]
  2347. }]
  2348. },
  2349. TVHoard: {
  2350. host: ['tvhoard.com'],
  2351. condition: Always,
  2352. products: [{
  2353. 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'),
  2354. type: 'movie',
  2355. data: () => document.querySelector('app-root title-page-container h1.title a').textContent.trim()
  2356. },
  2357. {
  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: 'tv',
  2360. data: () => document.querySelector('app-root title-page-container h1.title a').textContent.trim()
  2361. }]
  2362. },
  2363. AMC: {
  2364. host: ['amc.com'],
  2365. condition: () => document.location.pathname.startsWith('/shows/'),
  2366. products: [
  2367. {
  2368. condition: () => document.querySelector('.feeds[itemtype="http://schema.org/TVSeries"] h1'),
  2369. type: 'tv',
  2370. data: () => document.querySelector('.feeds[itemtype="http://schema.org/TVSeries"] h1').textContent
  2371. },
  2372. {
  2373. condition: () => document.location.pathname.split('/').length === 3 && document.querySelector("meta[property='og:type']") && document.querySelector("meta[property='og:type']").content.indexOf('tv_show') !== -1,
  2374. type: 'tv',
  2375. data: () => document.querySelector('.video-card-description h1').textContent.trim()
  2376. }]
  2377. },
  2378. AMCplus: {
  2379. host: ['amcplus.com'],
  2380. condition: () => Always,
  2381. products: [
  2382. {
  2383. condition: () => document.title.match(/Watch .+? |/),
  2384. type: 'tv',
  2385. data: () => document.title.match(/Watch (.+?) |/)[1].trim()
  2386. }]
  2387. },
  2388. RlsBB: {
  2389. host: ['rlsbb.ru'],
  2390. condition: () => document.querySelectorAll('.post').length === 1,
  2391. products: [
  2392. {
  2393. condition: () => document.querySelector('#post-wrapper .entry-meta a[href*="/category/movies/"]'),
  2394. type: 'movie',
  2395. data: () => document.querySelector('h1.entry-title').textContent.match(/(.+?)\s+\d{4}/)[1].trim()
  2396. },
  2397. {
  2398. condition: () => document.querySelector('#post-wrapper .entry-meta a[href*="/category/tv-shows/"]'),
  2399. type: 'tv',
  2400. data: () => document.querySelector('h1.entry-title').textContent.match(/(.+?)\s+S\d{2}/)[1].trim()
  2401. }]
  2402. },
  2403. newalbumreleases: {
  2404. host: ['newalbumreleases.net'],
  2405. condition: () => document.querySelectorAll('#content .single').length === 1,
  2406. products: [
  2407. {
  2408. condition: () => document.querySelector('#content .single .cover .entry'),
  2409. type: 'music',
  2410. data: function () {
  2411. const mArtist = document.querySelector('#content .single .cover .entry').textContent.match(/Artist.\s*(.+)\s+/i)
  2412. if (mArtist) {
  2413. const mAlbum = document.querySelector('#content .single .cover .entry').textContent.match(/Album.\s*(.+)\s+/i)
  2414. if (mAlbum) {
  2415. return [mArtist[1], mAlbum[1]]
  2416. }
  2417. }
  2418. }
  2419. }]
  2420. },
  2421. showtime: {
  2422. host: ['sho.com'],
  2423. condition: Always,
  2424. products: [
  2425. {
  2426. condition: () => parseLDJSON('@type') === 'Movie',
  2427. type: 'movie',
  2428. data: () => parseLDJSON('name', (j) => (j['@type'] === 'Movie'))
  2429. },
  2430. {
  2431. condition: () => parseLDJSON('@type') === 'TVSeries',
  2432. type: 'tv',
  2433. data: () => parseLDJSON('name', (j) => (j['@type'] === 'TVSeries'))
  2434. }]
  2435. },
  2436. epicgames: {
  2437. host: ['www.epicgames.com', 'store.epicgames.com'],
  2438. condition: () => document.querySelector('.meta-schema'),
  2439. products: [{
  2440. condition: Always,
  2441. type: 'pcgame',
  2442. data: () => document.querySelector('.meta-schema').nextElementSibling.firstElementChild.lastElementChild.firstElementChild.firstElementChild.firstElementChild.textContent
  2443. }]
  2444. },
  2445. gog: {
  2446. host: ['www.gog.com'],
  2447. condition: () => document.querySelector('.productcard-basics__title'),
  2448. products: [
  2449. {
  2450. condition: () => document.location.pathname.slice(1, 5) === 'game',
  2451. type: 'pcgame',
  2452. data: () => document.querySelector('.productcard-basics__title').textContent
  2453. },
  2454. {
  2455. condition: () => document.location.pathname.slice(1, 6) === 'movie',
  2456. type: 'movie',
  2457. data: () => document.querySelector('.productcard-basics__title').textContent
  2458. }
  2459. ]
  2460. },
  2461. steamgifts: {
  2462. host: ['www.steamgifts.com'],
  2463. condition: () => document.querySelector('.featured__heading__medium'),
  2464. products: [{
  2465. condition: Always,
  2466. type: 'pcgame',
  2467. data: () => document.querySelector('.featured__heading__medium').innerText
  2468. }]
  2469. },
  2470. allmusic: {
  2471. host: ['allmusic.com'],
  2472. condition: Always,
  2473. products: [{
  2474. condition: () => document.location.pathname.indexOf('/album/') !== -1,
  2475. type: 'music',
  2476. data: function () {
  2477. const ld = parseLDJSON(['name', 'byArtist'], (j) => (j['@type'] === 'MusicAlbum'))
  2478. const album = ld[0]
  2479. const artist = 'name' in ld[1] ? ld[1].name : ld[1].map(x => x.name).join(' ')
  2480. return [artist, album]
  2481. }
  2482. }]
  2483. }
  2484.  
  2485. }
  2486.  
  2487. async function main () {
  2488. let dataFound = false
  2489.  
  2490. let map = false
  2491.  
  2492. for (const name in sites) {
  2493. const site = sites[name]
  2494. if (site.host.some(function (e) { return ~this.indexOf(e) }, document.location.hostname) && site.condition()) {
  2495. for (let i = 0; i < site.products.length; i++) {
  2496. if (site.products[i].condition()) {
  2497. // Check map for a match
  2498. if (map === false) {
  2499. map = JSON.parse(await GM.getValue('map', '{}'))
  2500. }
  2501. const docurl = filterUniversalUrl(document.location.href)
  2502. if (docurl in map) {
  2503. // Found in map, show result
  2504. const metaurl = map[docurl]
  2505. metacriticGeneralProductSetup()
  2506. metacritic.mapped.apply(undefined, [docurl, site.products[i], absoluteMetaURL(metaurl), site.products[i].type])
  2507. dataFound = true
  2508. break
  2509. }
  2510. // Try to retrieve item name from page
  2511. let data
  2512. try {
  2513. data = site.products[i].data()
  2514. } catch (e) {
  2515. data = false
  2516. console.error(`ShowMetacriticRatings: Error in data() of site='${name}', type='${site.products[i].type}'`)
  2517. console.error(e)
  2518. }
  2519. if (data) {
  2520. const params = [docurl, site.products[i]]
  2521. if (Array.isArray(data)) {
  2522. params.push(...data)
  2523. } else {
  2524. params.push(data)
  2525. }
  2526. metacriticGeneralProductSetup()
  2527. metacritic[site.products[i].type].apply(undefined, params)
  2528. dataFound = true
  2529. }
  2530. break
  2531. }
  2532. }
  2533. break
  2534. }
  2535. }
  2536. return dataFound
  2537. }
  2538.  
  2539. (async function () {
  2540. const gdpr = await acceptGDPR()
  2541. if (!gdpr) {
  2542. GM.registerMenuCommand('Show Metacritic.com ratings - Accept terms of service', () => acceptGDPR(true).then((yes) => yes && document.location.reload()))
  2543. return
  2544. }
  2545. await versionUpdate()
  2546. const firstRunResult = await main()
  2547.  
  2548. GM.registerMenuCommand('Show Metacritic.com ratings - Search now', () => openSearchBox())
  2549.  
  2550. let lastLoc = document.location.href
  2551. let lastContent = document.body.innerText
  2552. let lastCounter = 0
  2553. async function newpage () {
  2554. if (lastContent === document.body.innerText && lastCounter < 15) {
  2555. window.setTimeout(newpage, 500)
  2556. lastCounter++
  2557. } else {
  2558. lastContent = document.body.innerText
  2559. lastCounter = 0
  2560. const re = await main()
  2561. if (!re) { // No page matched or no data found
  2562. window.setTimeout(newpage, 1000)
  2563. }
  2564. }
  2565. }
  2566. window.setInterval(function () {
  2567. if (document.location.href !== lastLoc) {
  2568. lastLoc = document.location.href
  2569. $('#mcdiv123').remove()
  2570.  
  2571. window.setTimeout(newpage, 1000)
  2572. }
  2573. }, 500)
  2574.  
  2575. if (!firstRunResult) {
  2576. // Initial run had no match, let's try again there may be new content
  2577. window.setTimeout(main, 2000)
  2578. }
  2579. })()