Show Metacritic.com ratings

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

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

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