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), TV.com, Steam, Gamespot (PS4, XONE, PC), Rotten Tomatoes, Serienjunkies, BoxOfficeMojo, allmovie.com, movie.com, Wikipedia (en), themoviedb.org, letterboxd, TVmaze, TVGuide, followshows.com, TheTVDB.com, ConsequenceOfSound, Pitchfork, Last.fm, TVRage.com, rateyourmusic.com

当前为 2017-05-06 提交的版本,查看 最新版本

  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), TV.com, Steam, Gamespot (PS4, XONE, PC), Rotten Tomatoes, Serienjunkies, BoxOfficeMojo, allmovie.com, movie.com, Wikipedia (en), themoviedb.org, letterboxd, TVmaze, TVGuide, followshows.com, TheTVDB.com, ConsequenceOfSound, Pitchfork, Last.fm, TVRage.com, rateyourmusic.com
  4. // @namespace cuzi
  5. // @oujs:author cuzi
  6. // @grant GM_xmlhttpRequest
  7. // @grant GM_setValue
  8. // @grant GM_getValue
  9. // @grant unsafeWindow
  10. // @require http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
  11. // @license GNUGPL
  12. // @version 25
  13. // @connect metacritic.com
  14. // @connect php-cuzi.rhcloud.com
  15. // @include https://*.bandcamp.com/*
  16. // @include https://itunes.apple.com/*/album/*
  17. // @include https://play.google.com/store/music/album/*
  18. // @include https://play.google.com/store/movies/details/*
  19. // @include http://www.amazon.com/*
  20. // @include https://www.amazon.com/*
  21. // @include http://www.amazon.co.uk/*
  22. // @include https://www.amazon.co.uk/*
  23. // @include http://www.amazon.fr/*
  24. // @include https://www.amazon.fr/*
  25. // @include http://www.amazon.de/*
  26. // @include https://www.amazon.de/*
  27. // @include http://www.amazon.es/*
  28. // @include https://www.amazon.es/*
  29. // @include http://www.amazon.ca/*
  30. // @include https://www.amazon.ca/*
  31. // @include http://www.amazon.in/*
  32. // @include https://www.amazon.in/*
  33. // @include http://www.amazon.it/*
  34. // @include https://www.amazon.it/*
  35. // @include http://www.amazon.co.jp/*
  36. // @include https://www.amazon.co.jp/*
  37. // @include http://www.amazon.com.mx/*
  38. // @include https://www.amazon.com.mx/*
  39. // @include http://www.amazon.com.au/*
  40. // @include https://www.amazon.com.au/*
  41. // @include http://www.imdb.com/title/*
  42. // @include https://www.imdb.com/title/*
  43. // @include http://store.steampowered.com/app/*
  44. // @include https://store.steampowered.com/app/*
  45. // @include http://www.gamespot.com/*
  46. // @include https://www.gamespot.com/*
  47. // @include http://www.serienjunkies.de/*
  48. // @include https://www.serienjunkies.de/*
  49. // @include http://www.tv.com/shows/*
  50. // @include http://www.rottentomatoes.com/m/*
  51. // @include https://www.rottentomatoes.com/m/*
  52. // @include http://www.rottentomatoes.com/tv/*
  53. // @include https://www.rottentomatoes.com/tv/*
  54. // @include http://www.rottentomatoes.com/tv/*/s*/
  55. // @include https://www.rottentomatoes.com/tv/*/s*/
  56. // @include http://www.boxofficemojo.com/movies/*
  57. // @include http://www.allmovie.com/movie/*
  58. // @include https://en.wikipedia.org/*
  59. // @include http://www.movies.com/*/m*
  60. // @include https://www.themoviedb.org/movie/*
  61. // @include https://www.themoviedb.org/tv/*
  62. // @include http://letterboxd.com/film/*
  63. // @include https://letterboxd.com/film/*
  64. // @include http://www.tvmaze.com/shows/*
  65. // @include http://www.tvguide.com/tvshows/*
  66. // @include https://www.tvguide.com/tvshows/*
  67. // @include http://followshows.com/show/*
  68. // @include https://followshows.com/show/*
  69. // @include http://thetvdb.com/*tab=series*
  70. // @include https://thetvdb.com/*tab=series*
  71. // @include http://consequenceofsound.net/*
  72. // @include https://consequenceofsound.net/*
  73. // @include http://pitchfork.com/*
  74. // @include http://www.last.fm/*
  75. // @include https://www.last.fm/*
  76. // @include http://www.tvrage.com/*
  77. // @include http://rateyourmusic.com/release/album/*
  78. // @include https://rateyourmusic.com/release/album/*
  79. // @include https://open.spotify.com/*
  80. // @include https://play.spotify.com/album/*
  81. // ==/UserScript==
  82.  
  83.  
  84. // ########## Conversion from Script Version 15 to 16+ ######
  85. // Type of "black" value changed from {} to []
  86. if(!("length" in JSON.parse(GM_getValue("black","[]")))) {
  87. GM_setValue("black","[]");
  88. }
  89. // ########## ######
  90.  
  91.  
  92. var baseURL = "http://www.metacritic.com/";
  93.  
  94. var baseURL_music = "http://www.metacritic.com/music/";
  95. var baseURL_movie = "http://www.metacritic.com/movie/";
  96. var baseURL_pcgame = "http://www.metacritic.com/game/pc/";
  97. var baseURL_ps4 = "http://www.metacritic.com/game/playstation-4/";
  98. var baseURL_xone = "http://www.metacritic.com/game/xbox-one/";
  99. var baseURL_tv = "http://www.metacritic.com/tv/";
  100.  
  101. var baseURL_search = "http://www.metacritic.com/search/{type}/{query}/results";
  102. var baseURL_autosearch = "http://www.metacritic.com/autosearch";
  103.  
  104. var baseURL_database = "https://php-cuzi.rhcloud.com/r.php";
  105. var baseURL_whitelist = "https://php-cuzi.rhcloud.com/whitelist.php";
  106. var baseURL_blacklist = "https://php-cuzi.rhcloud.com/blacklist.php";
  107.  
  108. var mybrowser = "other";
  109. if(~navigator.userAgent.indexOf("Chrome")) {
  110. mybrowser = "chrome";
  111. }
  112.  
  113. // http://www.designcouch.com/home/why/2013/05/23/dead-simple-pure-css-loading-spinner/
  114. var CSS = "#mcdiv123 .grespinner{height:16px;width:16px;margin:0 auto;position:relative;-webkit-animation:rotation .6s infinite linear;-moz-animation:rotation .6s infinite linear;-o-animation:rotation .6s infinite linear;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%}@-webkit-keyframes rotation{from{-webkit-transform:rotate(0)}to{-webkit-transform:rotate(359deg)}}@-moz-keyframes rotation{from{-moz-transform:rotate(0)}to{-moz-transform:rotate(359deg)}}@-o-keyframes rotation{from{-o-transform:rotate(0)}to{-o-transform:rotate(359deg)}}@keyframes rotation{from{transform:rotate(0)}to{transform:rotate(359deg)}}#mcdiv123searchresults .result{font:12px arial,helvetica,serif;border-top-width:1px;border-top-color:#ccc;border-top-style:solid;padding:5px}#mcdiv123searchresults .result .result_type{display:inline}#mcdiv123searchresults .result .result_wrap{float:left;width:100%}#mcdiv123searchresults .result .has_score{padding-left:42px}#mcdiv123searchresults .result .basic_stats{height:1%;overflow:hidden}#mcdiv123searchresults .result h3{font-size:14px;font-weight:700}#mcdiv123searchresults .result a{color:#09f;font-weight:700;text-decoration:none}#mcdiv123searchresults .metascore_w.game.seventyfive,#mcdiv123searchresults .metascore_w.positive,#mcdiv123searchresults .metascore_w.score_favorable,#mcdiv123searchresults .metascore_w.score_outstanding,#mcdiv123searchresults .metascore_w.sixtyone{background-color:#6c3}#mcdiv123searchresults .metascore_w.forty,#mcdiv123searchresults .metascore_w.game.fifty,#mcdiv123searchresults .metascore_w.mixed,#mcdiv123searchresults .metascore_w.score_mixed{background-color:#fc3}#mcdiv123searchresults .metascore_w.negative,#mcdiv123searchresults .metascore_w.score_terrible,#mcdiv123searchresults .metascore_w.score_unfavorable{background-color:red}#mcdiv123searchresults a.metascore_w,#mcdiv123searchresults span.metascore_w{display:inline-block}#mcdiv123searchresults .result .metascore_w{color:#fff!important;font-family:Arial,Helvetica,sans-serif;font-size:17px;font-style:normal!important;font-weight:700!important;height:2em;line-height:2em;text-align:center;vertical-align:middle;width:2em;float:left;margin:0 0 0 -42px}#mcdiv123searchresults .result .more_stats{font-size:10px;color:#444}#mcdiv123searchresults .result .release_date .data{font-weight:700;color:#000}#mcdiv123searchresults ol,#mcdiv123searchresults ul{list-style:none}#mcdiv123searchresults .result li.stat{background:0 0;display:inline;float:left;margin:0;padding:0 6px 0 0;white-space:nowrap}#mcdiv123searchresults .result .deck{margin:3px 0 0}#mcdiv123searchresults .result .basic_stat{display:inline;float:right;overflow:hidden;width:100%}";
  115.  
  116. function getHostname(url) {
  117. with(document.createElement("a")) {
  118. href = url;
  119. return hostname;
  120. }
  121. }
  122. function name2metacritic(s) {
  123. return s.normalize('NFKD').replace(/\//g,"").replace(/[\u0300-\u036F]/g, '').replace(/&/g,"and").replace(/\W+/g, " ").toLowerCase().trim().replace(/\W+/g,"-");
  124. }
  125. function minutesSince(time) {
  126. var seconds = ((new Date()).getTime() - time.getTime()) / 1000;
  127. return seconds>60?parseInt(seconds/60)+" min ago":"now";
  128. }
  129. function randomStringId() {
  130. var id10 = () => Math.floor((1 + Math.random()) * 0x10000000000).toString(16).substring(1);
  131. return id10()+id10()+id10()+id10()+id10()+id10();
  132. }
  133. function fixMetacriticURLs(html) {
  134. return html.replace(/<a /g,'<a target="_blank" ').replace(/href="\//g,'href="'+baseURL).replace(/src="\//g,'src="'+baseURL);
  135. }
  136. function searchType2metacritic(type) {
  137. return ({
  138. 'movie' : 'movie',
  139. 'pcgame' : 'game',
  140. 'xonegame' : 'game',
  141. 'ps4game' : 'game',
  142. 'music' : 'album',
  143. 'tv' : 'tv'
  144. })[type];
  145. }
  146. function metacritic2searchType(type) {
  147. return ({
  148. "Album" : "music",
  149. "TV" : "tv",
  150. "Movie" : "movie",
  151. "PC Game" : "pcgame",
  152. "PS4 Game" : "ps4game",
  153. "XONE Game" : "onegame",
  154. "WIIU Game" : "xxxxx",
  155. "3DS Game" : "xxxx"
  156. })[type];
  157. }
  158.  
  159.  
  160. function metaScore(score, word) {
  161. var fg,bg,t;
  162. if(score == null) {
  163. fg = "black";
  164. bg = "#ccc";
  165. t = "tbd";
  166. } else if(score >= 75) {
  167. fg = "white";
  168. bg = "#6c3";
  169. t = parseInt(score);
  170. } else if(score < 40) {
  171. fg = "white";
  172. bg = "#f00";
  173. t = parseInt(score);
  174. } else {
  175. fg = "white";
  176. bg = "#fc3";
  177. t = parseInt(score);
  178. }
  179. return '<span title="'+(word?word:'')+'" style="display: inline-block; color: '+fg+';background:'+bg+';font-family: Arial,Helvetica,sans-serif;font-size: 17px;font-style: normal;font-weight: bold;height: 2em;width: 2em;line-height: 2em;text-align: center;vertical-align: middle;">'+t+'</span>';
  180. }
  181.  
  182. function balloonAlert(message, timeout, title, css, click) {
  183. var header;
  184. if(title) {
  185. header = '<div style="background:rgb(220,230,150); padding: 2px 12px;">' + title +"</div>";
  186. } else if(title === false) {
  187. header = '';
  188. } else {
  189. header = '<div style="background:rgb(220,230,150); padding: 2px 12px;">Userscript alert</div>';
  190. }
  191. var div = $("<div>" + header + '<div style="padding:5px">' + message.split("\n").join("<br>") + "</div></div>");
  192. div.css({
  193. position : "fixed",
  194. top : 10,
  195. left : 10,
  196. maxWidth: 200,
  197. zIndex : "5010002",
  198. background : "rgb(240,240,240)",
  199. border : "2px solid yellow",
  200. borderRadius :"6px",
  201. boxShadow: "0 0 3px 3px rgba(100, 100, 100, 0.2)",
  202. fontFamily: "sans-serif",
  203. color: "black"
  204. });
  205. if(css) {
  206. div.css(css);
  207. }
  208. div.appendTo(document.body);
  209. if(click) {
  210. div.click(function(ev) {
  211. $(this).hide(500);
  212. click.call(this,ev);
  213. });
  214. }
  215. if(!click) {
  216. var close = $('<div title="Close" style="cursor:pointer; position:absolute; top:0px; right:3px;">&#10062;</div>').appendTo(div);
  217. close.click(function(){
  218. $(this.parentNode).hide(1000);
  219. });
  220. }
  221. if(timeout && timeout > 0) {
  222. window.setTimeout(function() {
  223. div.hide(3000);
  224. }, timeout);
  225. }
  226. return div;
  227. }
  228.  
  229.  
  230. function filterUniversalUrl(url) {
  231. try {
  232. url = url.match(/http.+/)[0];
  233. } catch(e) { }
  234. try {
  235. url = url.replace(/https?:\/\/(www.)?/,"");
  236. } catch(e) { }
  237. if(url.startsWith("imdb.com/") && url.match(/(imdb\.com\/\w+\/\w+\/)/)) {
  238. // Remove movie subpage from imdb url
  239. return url.match(/(imdb\.com\/\w+\/\w+\/)/)[1];
  240. } else if(url.startsWith("thetvdb.com/")) {
  241. // Do nothing with thetvdb.com urls
  242. return url;
  243. } else {
  244. // Default: Remove parameters
  245. return url.split("?")[0].split("&")[0];
  246. }
  247. }
  248.  
  249. function addToMap(url, metaurl) {
  250. var data = JSON.parse(GM_getValue("map","{}"));
  251. var url = filterUniversalUrl(url);
  252. var metaurl = metaurl.replace(/^http:\/\/(www.)?metacritic\.com\//,"");
  253.  
  254. data[url] = metaurl;
  255. GM_setValue("map", JSON.stringify(data));
  256. (new Image()).src = baseURL_whitelist + "?docurl="+encodeURIComponent(url)+"&metaurl="+encodeURIComponent(metaurl)+"&ref="+encodeURIComponent(randomStringId());
  257. return [url, metaurl];
  258. }
  259.  
  260. function addToBlacklist(url, metaurl) {
  261. var data = JSON.parse(GM_getValue("black","[]"));
  262. var url = filterUniversalUrl(url);
  263. var metaurl = metaurl.replace(/^http:\/\/(www.)?metacritic\.com\//,"");
  264.  
  265. data.push([url,metaurl]);
  266. GM_setValue("black", JSON.stringify(data));
  267. (new Image()).src = baseURL_blacklist + "?docurl="+encodeURIComponent(url)+"&metaurl="+encodeURIComponent(metaurl)+"&ref="+encodeURIComponent(randomStringId());
  268. return [url, metaurl];
  269. }
  270.  
  271.  
  272.  
  273.  
  274. function isBlacklistedUrl(docurl, metaurl) {
  275.  
  276. docurl = filterUniversalUrl(docurl);
  277. docurl = docurl.replace(/https?:\/\/(www.)?/,"");
  278. metaurl = metaurl.replace(/^http:\/\/(www.)?metacritic\.com\//,"");
  279. metaurl = metaurl.replace(/\/\//g,"/").replace(/\/\//g,"/");; // remove double slash
  280. metaurl = metaurl.replace(/^\/+/,""); // remove starting slash
  281. var data = JSON.parse(GM_getValue("black","[]")); // [ [docurl0, metaurl0] , [docurl1, metaurl1] , ... ]
  282. for(var i = 0; i < data.length; i++) {
  283. if(data[i][0] == docurl && data[i][1] == metaurl) {
  284. return true;
  285. }
  286. }
  287. return false;
  288. }
  289.  
  290. function isBlacklisted(metaurl) {
  291. return isBlacklistedUrl("" + document.location.host.replace(/^www\./,"") + document.location.pathname + document.location.search, metaurl);
  292. }
  293.  
  294.  
  295.  
  296. function listenForHotkeys(code, cb) {
  297. // Call cb() as soon as the code sequence was typed
  298. var i = 0;
  299. $(document).bind("keydown.listenForHotkeys",function(ev) {
  300. if(document.activeElement == document.body) {
  301. if(ev.key != code[i]) {
  302. i = 0;
  303. } else {
  304. i++;
  305. if(i == code.length) {
  306. ev.preventDefault();
  307. $(document).unbind("keydown.listenForHotkeys");
  308. cb();
  309. }
  310. }
  311. }
  312. });
  313. }
  314.  
  315.  
  316. function metacritic_hoverInfo(url, docurl, cb, errorcb) {
  317. // Get the metacritic hover info. Requests are cached.
  318. var handleresponse = function(response, cached) {
  319. if(response.status == 200 && response.responseText && cb) {
  320. if(~response.responseText.indexOf('"jsonRedirect"')) { // {"viewer":{},"mixpanelToken":"6e219fd....","mixpanelDistinctId":"255.255.255.255","omnitureDebug":0,"jsonRedirect":"\/movie\/national-lampoons-vacation"}
  321. var blacklistedredirect = false;
  322. var j = JSON.parse(response.responseText);
  323. current.url = baseURL + j["jsonRedirect"];
  324. delete cache[url]; // Delete original url from cache. The redirect URL will then be saved in metacritic_hoverInfo(...)
  325.  
  326. // Blacklist items from database received?
  327. if("blacklist" in j && j.blacklist && j.blacklist.length) {
  328. // Save new blacklist items
  329. var data = JSON.parse(GM_getValue("black","[]"));
  330. for(var i = 0; i < j.blacklist.length; i++) {
  331. var save_docurl = j.blacklist[i].docurl;
  332. var save_metaurl = j.blacklist[i].metaurl;
  333. data.push([save_docurl,save_metaurl]);
  334. if(j["jsonRedirect"] == "/"+save_metaurl) {
  335. // Redirect is blacklisted!
  336. blacklistedredirect = true;
  337. }
  338. }
  339. GM_setValue("black", JSON.stringify(data));
  340. }
  341. if(blacklistedredirect && errorcb) {
  342. // Redirect was blacklisted, show nothing
  343. errorcb(response.responseText, new Date(response.time));
  344. } else {
  345. // Load redirect
  346. metacritic_hoverInfo(baseURL + j["jsonRedirect"], false, cb, errorcb);
  347. }
  348. } else {
  349. cb(response.responseText, new Date(response.time));
  350. }
  351. } else if(response.status != 200 && errorcb) {
  352. errorcb(response.responseText, new Date(response.time));
  353. if(!cached)
  354. console.log("Show metacritic ratings: Error:"+response.status+"\n"+url);
  355. } else if(!response.responseText) {
  356. errorcb("", new Date(response.time));
  357. if(!cached)
  358. console.log("Show metacritic ratings: Error: response empty. Status:"+response.status+"\n"+url);
  359. }
  360. };
  361. var cache = JSON.parse(GM_getValue("hovercache","{}"));
  362. for(var prop in cache) {
  363. // Delete cached values, that are older than 2 hours
  364. if((new Date()).getTime() - (new Date(cache[prop].time)).getTime() > 2*60*60*1000) {
  365. delete cache[prop];
  366. }
  367. }
  368. if(url in cache) {
  369. handleresponse(cache[url], true);
  370. } else {
  371. var requestURL = url;
  372. var requestParams = "hoverinfo=1";
  373. if(docurl && docurl.indexOf("metacritic.com") == -1 && docurl.indexOf(baseURL_database) == -1) {
  374. // Ask database for correct metacritic entry:
  375. requestURL = baseURL_database;
  376. requestParams = "m=" + encodeURIComponent(docurl) + "&a=" + encodeURIComponent(url);
  377. }
  378. GM_xmlhttpRequest({
  379. method: "POST",
  380. url: requestURL,
  381. data: requestParams,
  382. headers: {
  383. "Referer" : url,
  384. "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8",
  385. "Host" : getHostname(requestURL), // This is important, otherwise Metacritic refuses to answer!
  386. "User-Agent" : "MetacriticUserscript "+navigator.userAgent,
  387. "X-Requested-With" : "XMLHttpRequest"
  388. },
  389. onload: function(response) {
  390. response.time = (new Date()).toJSON();
  391. cache[url] = response;
  392. GM_setValue("hovercache",JSON.stringify(cache));
  393. handleresponse(response, false);
  394. },
  395. onerror: function(response) {
  396. console.log("Show metacritic ratings: Hover info error: "+response.status+"\nURL: "+requestURL+"\nResponse:\n"+response.responseText);
  397. },
  398. });
  399. }
  400. }
  401. function metacritic_searchResults(url, cb, errorcb) {
  402. // Get metacritic search results. Requests are cached.
  403. var handleresponse = function(response, cached) {
  404. if(response.results.length && cb) {
  405. cb(response.results, new Date(response.time));
  406. } else if(response.results.length == 0 && errorcb) {
  407. errorcb(response.results, new Date(response.time));
  408. }
  409. };
  410. var cache = JSON.parse(GM_getValue("searchcache","{}"));
  411. for(var prop in cache) {
  412. // Delete cached values, that are older than 2 hours
  413. if((new Date()).getTime() - (new Date(cache[prop].time)).getTime() > 2*60*60*1000) {
  414. delete cache[prop];
  415. }
  416. }
  417. if(url in cache) {
  418. handleresponse(cache[url], true);
  419. } else {
  420. GM_xmlhttpRequest({
  421. method: "GET",
  422. url: url,
  423. headers: {
  424. "Referer" : url,
  425. "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8",
  426. "Host" : "www.metacritic.com",
  427. "User-Agent" : "MetacriticUserscript "+navigator.userAgent,
  428. },
  429. onload: function(response) {
  430. var results = [];
  431. if(!~response.responseText.indexOf("No search results found.")) {
  432. var d = $('<html>').html(response.responseText);
  433. d.find("ul.search_results.module .result").each(function() {
  434. results.push(this.innerHTML);
  435. });
  436. }
  437.  
  438. response = {
  439. time : (new Date()).toJSON(),
  440. results : results,
  441. };
  442. cache[url] = response;
  443. GM_setValue("searchcache",JSON.stringify(cache));
  444. handleresponse(response, false);
  445. },
  446. onerror: function(response) {
  447. console.log("Show metacritic ratings: Search error: "+response.status+"\n"+url);
  448. handleresponse({
  449. time : (new Date()).toJSON(),
  450. results : [],
  451. }, false);
  452. }
  453. });
  454. }
  455. }
  456.  
  457. function metacritic_showHoverInfo(url, docurl) {
  458. if(!url) {
  459. return;
  460. }
  461. metacritic_hoverInfo(url, docurl?docurl:false,
  462. // On Success
  463. function(html, time) {
  464. $("#mcdiv123").remove();
  465. var div = $('<div id="mcdiv123"></div>').appendTo(document.body);
  466. div.css({
  467. position:"fixed",
  468. bottom :0,
  469. left: 0,
  470. minWidth: 300,
  471. backgroundColor: "#fff",
  472. border: "2px solid #bbb",
  473. borderRadius:" 6px",
  474. boxShadow: "0 0 3px 3px rgba(100, 100, 100, 0.2)",
  475. color: "#000",
  476. padding:" 3px",
  477. zIndex: "5010001",
  478. });
  479. // Functions for communication between page and iframe
  480. // Mozilla can access parent.document
  481. // Chrome can use postMessage()
  482. var frame_status = false; // if this remains false, loading the frame content failed. A reason could be "Content Security Policy"
  483. function loadExternalImage(url, myframe) {
  484. // Load external image, bypass CSP
  485. GM_xmlhttpRequest({
  486. method: "GET",
  487. url: url,
  488. responseType : "arraybuffer",
  489. onload: function(response) {
  490. myframe.contentWindow.postMessage({
  491. "mcimessage_imgLoaded" : true,
  492. "mcimessage_imgData" : response.response,
  493. "mcimessage_imgOrgSrc" : url
  494. },'*');
  495. }
  496. });
  497. }
  498. var functions = {
  499. "other" : {
  500. "parent": function() {
  501. var f = parent.document.getElementById('mciframe123');
  502. window.addEventListener("message", function(e){
  503. if(typeof e.data != "object") {
  504. return;
  505. } else if("mcimessage0" in e.data) {
  506. frame_status = true; // Frame content was loaded successfully
  507. } else if("mcimessage_loadImg" in e.data) {
  508. loadExternalImage(e.data.mcimessage_imgUrl, f);
  509. }
  510. });
  511. },
  512. "frame" : function sizecorrection() {
  513. parent.postMessage({"mcimessage0":true},'*'); // Loading frame content was successfull
  514. window.addEventListener("message", function(e){
  515. if(typeof e.data == "object" && "mcimessage_imgLoaded" in e.data) {
  516. // Load external image
  517. var arrayBufferView = new Uint8Array( e.data["mcimessage_imgData"] );
  518. var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
  519. var urlCreator = window.URL || window.webkitURL;
  520. var imageUrl = urlCreator.createObjectURL( blob );
  521. var img = failedImages[e.data["mcimessage_imgOrgSrc"]];
  522. img.src = imageUrl;
  523. }
  524. });
  525. var f = parent.document.getElementById('mciframe123');
  526. for(var i =0; f.clientHeight < document.body.scrollHeight && i < 100; i++) {
  527. f.style.width = parseInt(f.style.width)+10+"px";
  528. }
  529. if(f.clientHeight < document.body.scrollHeight) {
  530. f.style.height = parseInt(f.style.height)+15+"px";
  531. f.style.width = "300px";
  532. if(parseInt(f.style.height) > 500) {
  533. return;
  534. }
  535. sizecorrection();
  536. }
  537. }
  538. },
  539. "chrome" : {
  540. "parent" : function() {
  541. var f = parent.document.getElementById('mciframe123');
  542. window.addEventListener("message", function(e){
  543. if(typeof e.data != "object") {
  544. return;
  545. } else if("mcimessage0" in e.data) {
  546. frame_status = true; // Frame content was loaded successfully
  547. } else if("mcimessage1" in e.data) {
  548. f.style.width = parseInt(f.style.width)+10+"px";
  549. } else if("mcimessage2" in e.data) {
  550. f.style.height = parseInt(f.style.height)+15+"px";
  551. f.style.width = "300px";
  552. } else if("mcimessage_loadImg" in e.data) {
  553. loadExternalImage(e.data.mcimessage_imgUrl, f);
  554. } else {
  555. return;
  556. }
  557. f.contentWindow.postMessage({
  558. "mcimessage3" : true,
  559. "mciframe123_clientHeight" : f.clientHeight,
  560. "mciframe123_clientWidth" : f.clientWidth,
  561. },'*');
  562. });
  563. },
  564. "frame" : function() {
  565. parent.postMessage({"mcimessage0":true},'*'); // Loading frame content was successfull
  566. var i = 0;
  567. window.addEventListener("message", function(e){
  568. if(typeof e.data == "object" && "mcimessage_imgLoaded" in e.data) {
  569. // Load external image
  570. var arrayBufferView = new Uint8Array( e.data["mcimessage_imgData"] );
  571. var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
  572. var urlCreator = window.URL || window.webkitURL;
  573. var imageUrl = urlCreator.createObjectURL( blob );
  574. var img = failedImages[e.data["mcimessage_imgOrgSrc"]];
  575. img.src = imageUrl;
  576. }
  577. if(!("mcimessage3" in e.data)) return;
  578. if(e.data.mciframe123_clientHeight < document.body.scrollHeight && i < 100) {
  579. parent.postMessage({"mcimessage1":1},'*');
  580. i++;
  581. }
  582. if(i >= 100) {
  583. parent.postMessage({"mcimessage2":1},'*')
  584. i = 0;
  585. }
  586. });
  587. parent.postMessage({"mcimessage1":1},'*');
  588. }
  589. }
  590. };
  591.  
  592. var css = "#hover_div .clr { clear: both}#hover_div { background-color: #fff; color: #666; font-family:Arial,Helvetica,sans-serif; font-size:12px; font-weight:400; font-style:normal;} #hover_div .hoverinfo .hover_left { float: left} #hover_div .hoverinfo .product_image_wrapper { color: #999; font-size: 6px; font-weight: normal; min-height: 98px; min-width: 98px;} #hover_div .hoverinfo .product_image_wrapper a { color: #999; font-size: 6px; font-weight: normal;} #hover_div a * { cursor: pointer}a { color: #09f; font-weight: bold;} #hover_div a:link, #hover_div a:visited { text-decoration: none;} #hover_div a:hover { text-decoration: underline;} #hover_div .hoverinfo .hover_right { float: left; margin-left: 15px; max-width: 395px;} #hover_div .hoverinfo .product_title { color: #333; font-family: georgia,serif; font-size: 24px; line-height: 26px; margin-bottom: 10px;} #hover_div .hoverinfo .product_title a { color:#333; font-family: georgia,serif; font-size: 24px;} #hover_div .hoverinfo .summary_detail.publisher, .hoverinfo .summary_detail.release_data { float: left} #hover_div .hoverinfo .summary_detail { font-size: 11px; margin-bottom: 10px;} #hover_div .hoverinfo .summary_detail.product_credits a { color: #999; font-weight: normal; } #hover_div .hoverinfo .hr { background-color: #ccc; height: 2px; margin: 15px 0 10px;} #hover_div .hoverinfo .hover_scores { width: 100%; border-collapse: collapse; border-spacing: 0;} #hover_div .hoverinfo .hover_scores td.num { width: 39px} #hover_div .hoverinfo .hover_scores td { vertical-align: middle} #hover_div caption, #hover_div th, #hover_div td { font-weight: normal; text-align: left;} #hover_div .metascore_anchor, #hover_div a.metascore_w { text-decoration: none !important} #hover_div span.metascore_w, #hover_div a.metascore_w { display: inline-block; padding:0px;}.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;} #hover_div .metascore, #hover_div .metascore a, #hover_div .avguserscore, #hover_div .avguserscore a { color: #fff} #hover_div .critscore, #hover_div .critscore a, #hover_div .userscore, #hover_div .userscore a { color: #333}.score_tbd { background: #eaeaea; color: #333; font-size: 14px;}.score_tbd a { color: #333}.negative, .score_terrible, .score_unfavorable, .carousel_set a.product_terrible:hover, .carousel_set a.product_unfavorable:hover { background-color: #f00}.mixed, .neutral, .score_mixed, .carousel_set a.product_mixed:hover { background-color: #fc3; color: #333;}.score_mixed a { color: #333}.positive, .score_favorable, .score_outstanding, .carousel_set a.product_favorable:hover, .carousel_set a.product_outstanding:hover { background-color: #6c3}.critscore_terrible, .critscore_unfavorable { border-color: #f00}.critscore_mixed { border-color: #fc3}.critscore_favorable, .critscore_outstanding { border-color: #6c3}.metascore .score_total, .userscore .score_total { display: none; visibility: hidden;}.hoverinfo .metascore_label, .hoverinfo .userscore_label { font-size: 12px; font-weight: bold; line-height: 16px; margin-top: 2%;}.hoverinfo .metascore_review_count, .hoverinfo .userscore_review_count { font-size: 11px}.hoverinfo .hover_scores td { vertical-align: middle}.hoverinfo .hover_scores td.num { width: 39px}.hoverinfo .hover_scores td.usr.num { padding-left: 20px}.metascore_anchor, a.metascore_w { text-decoration: none !important}.metascore_w.user { border-radius: 55%; color: #fff;}.metascore_anchor, a.metascore_w { text-decoration: none!important}.metascore_anchor:hover { text-decoration: none!important}.metascore_w:hover { text-decoration: none!important}span.metascore_w, a.metascore_w { display: inline-block}.metascore_w.xlarge, .metascore_w.xl { font-size: 42px}.metascore_w.large, .metascore_w.lrg { font-size: 25px}.m .metascore_w.medium, .m .metascore_w.med { font-size: 19px}.metascore_w.med_small { font-size: 14px}.metascore_w.small, .metascore_w.sm { font-size: 12px}.metascore_w.tiny { height: 1.9em; font-size: 11px; line-height: 1.9em;}.metascore_w.user { border-radius: 55%; color: #fff;}.metascore_w.user.small, .metascore_w.user.sm { font-size: 11px}.metascore_w.tbd, .metascore_w.score_tbd { color: #000!important; background-color: #ccc;}.metascore_w.tbd.hide_tbd, .metascore_w.score_tbd.hide_tbd { visibility: hidden}.metascore_w.tbd.no_tbd, .metascore_w.score_tbd.no_tbd { display: none}.metascore_w.noscore::before, .metascore_w.score_noscore::before { content: '\2022\2022\2022'}.metascore_w.noscore, .metascore_w.score_noscore { color: #fff!important; background-color: #ccc;}.metascore_w.rip, .metascore_w.score_rip { border-radius: 4px; color: #fff!important; background-color: #999;}.metascore_w.negative, .metascore_w.score_terrible, .metascore_w.score_unfavorable { background-color: #f00}.metascore_w.mixed, .metascore_w.forty, .metascore_w.game.fifty, .metascore_w.score_mixed { background-color: #fc3}.metascore_w.positive, .metascore_w.sixtyone, .metascore_w.game.seventyfive, .metascore_w.score_favorable, .metascore_w.score_outstanding { background-color: #6c3}.metascore_w.indiv { height: 1.9em; width: 1.9em; font-size: 15px; line-height: 1.9em;}.metascore_w.indiv.large, .metascore_w.indiv.lrg { font-size: 24px}.m .metascore_w.indiv.medium, .m .metascore_w.indiv.med { font-size: 16px}.metascore_w.indiv.small, .metascore_w.indiv.sm { font-size: 11px}.metascore_w.indiv.perfect { padding-right: 1px}.promo_amazon .esite_btn { margin: 3px 0 0 7px;}.esite_amazon { background-color: #fdc354; border: 1px solid #aaa;}.esite_label_wrapper { display:none;}.esite_btn { border-radius: 4px; color: #222; font-size: 12px; height: 40px; line-height: 40px; width: 120px;}";
  593.  
  594. var framesrc = 'data:text/html,';
  595. framesrc += encodeURIComponent('<!DOCTYPE html>\
  596. <html lang="en">\
  597. <head>\
  598. <meta charset="utf-8">\
  599. <title>Metacritic info</title>\
  600. <style>body { margin:0px; padding:0px; background:white; }' + css
  601. +'\
  602. </style>\
  603. <script>\
  604. var failedImages = {};\
  605. function detectCSP(img) {\
  606. if(img.complete && (!img.naturalWidth || !img.naturalHeight)) {\
  607. return true;\
  608. }\
  609. return false;\
  610. }\
  611. function findCSPerrors() {\
  612. var imgs = document.querySelectorAll("img");\
  613. for(var i = 0; i < imgs.length; i++) {\
  614. if(imgs[i].complete && detectCSP(imgs[i])) {\
  615. fixCSP(imgs[i]);\
  616. }\
  617. }\
  618. }\
  619. function fixCSP(img) {\
  620. console.log("Loading image failed. Bypassing CSP...");\
  621. failedImages[img.src] = img;\
  622. parent.postMessage({"mcimessage_loadImg":true, "mcimessage_imgUrl": img.src},"*"); \
  623. }\
  624. function on_load() {\
  625. ('+functions[mybrowser].frame.toString()+')();\
  626. window.setTimeout(findCSPerrors, 500);\
  627. \
  628. }\
  629. </script>\
  630. </head>\
  631. <body onload="on_load();">\
  632. <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">\
  633. <div class="hover_content">'+fixMetacriticURLs(html)+'</div>\
  634. </div>\
  635. </body>\
  636. </html>');
  637. var frame = $("<iframe></iframe>").appendTo(div);
  638. frame.attr("id","mciframe123");
  639. frame.attr("src",framesrc);
  640. frame.attr("scrolling","auto");
  641. frame.css({
  642. width: 300,
  643. height: 170,
  644. border: "none"
  645. });
  646. window.setTimeout(function() {
  647. if(!frame_status) { // Loading frame content failed.
  648. // Directly inject the html without an iframe (this may break the site or the metacritic)
  649. console.log("Loading iframe content failed. Injecting directly.");
  650. $("head").append("<style>"+css+"</style>");
  651. var 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">\
  652. <div class="hover_content">'+fixMetacriticURLs(html)+'</div>\
  653. </div>');
  654. frame.replaceWith(noframe);
  655. }
  656. },2000);
  657. functions[mybrowser].parent();
  658. var sub = $("<div></div>").appendTo(div);
  659. $('<time style="color:#b6b6b6; font-size: 11px;" datetime="'+time+'" title="'+time.toLocaleTimeString()+" "+time.toLocaleDateString()+'">'+minutesSince(time)+'</time>').appendTo(sub);
  660. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="'+url+'" title="Open Metacritic">'+decodeURI(url.replace("http://www.","@"))+'</a>').appendTo(sub);
  661. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px; padding-left:5px;">&#10062;</span>').appendTo(sub).click(function() {
  662. document.body.removeChild(this.parentNode.parentNode);
  663. });
  664. $('<span title="Assist us: This is the correct entry!" style="cursor:pointer; float:right; color:green; font-size: 11px;">&check;</span>').data("url", url).appendTo(sub).click(function() {
  665. var docurl = document.location.href;
  666. var metaurl = $(this).data("url");
  667. var r = addToMap(docurl,metaurl);
  668. balloonAlert("Thanks for your submission!\n\nSaved as a correct entry.\n\n"+r[0]+"\n"+r[1], 6000, "Success");
  669. });
  670. $('<span title="Assist us: This is NOT the correct entry!" style="cursor:pointer; float:right; color:crimson; font-size: 11px;">&cross;</span>').data("url", url).appendTo(sub).click(function() {
  671. if(!confirm("This is NOT the correct entry!\n\nAdd to blacklist?")) return;
  672. var docurl = document.location.href;
  673. var metaurl = $(this).data("url");
  674. var r = addToBlacklist(docurl,metaurl);
  675. balloonAlert("Thanks for your submission!\n\nSaved to blacklist.\n\n"+r[0]+"\n"+r[1], 6000, "Success");
  676. // Open search
  677. metacritic_searchcontainer(null, current.searchTerm);
  678. metacritic_search(null, current.searchTerm);
  679. });
  680.  
  681. },
  682. // On error i.e. no result on metacritic.com
  683. function(html, time) {
  684. // Make search available
  685. metacritic_waitForHotkeys();
  686. var handleresponse = function(response) {
  687. var data;
  688. var multiple = false;
  689. try {
  690. data = JSON.parse(response.responseText);
  691. } catch(e) {
  692. console.log("Error in JSON: search_term="+current.searchTerm);
  693. console.log(e);
  694. }
  695. if(data && data.autoComplete && data.autoComplete.results && data.autoComplete.results.length) {
  696. // Remove data with wrong type
  697. data.autoComplete = data.autoComplete.results;
  698. var newdata = [];
  699. data.autoComplete.forEach(function(result) {
  700. if(metacritic2searchType(result.refType) == current.type) {
  701. newdata.push(result);
  702. }
  703. });
  704. data.autoComplete = newdata;
  705. if(data.autoComplete.length == 0) {
  706. // No results
  707. console.log("No results (after filtering by type) for search_term="+current.searchTerm);
  708. } else if(data.autoComplete.length == 1) {
  709. // One result, let's show it
  710. if(!isBlacklisted(baseURL + data.autoComplete[0].url)) {
  711. metacritic_showHoverInfo(baseURL + data.autoComplete[0].url);
  712. return;
  713. }
  714. } else {
  715. // More than one result
  716. multiple = true;
  717. console.log("Multiple results for search_term="+current.searchTerm);
  718. var exactMatches = [];
  719. data.autoComplete.forEach(function(result,i) { // Try to find the correct result by matching the search term to exactly one movie title
  720. if(current.searchTerm == result.name) {
  721. exactMatches.push(result);
  722. }
  723. });
  724. if(exactMatches.length == 1) {
  725. // Only one exact match, let's show it
  726. console.log("Only one exact match for search_term="+current.searchTerm);
  727. if(!isBlacklisted(baseURL + exactMatches[0].url)) {
  728. metacritic_showHoverInfo(baseURL + exactMatches[0].url);
  729. return;
  730. }
  731. }
  732. }
  733. } else {
  734. console.log("No results (at all) for search_term="+current.searchTerm);
  735. }
  736. // HERE: multiple results or no result. The user may type "meta" now
  737. if(multiple) {
  738. balloonAlert("Multiple metacritic results. Type &#34;meta&#34; for manual search.", 10000, false, {bottom: 5, top:"auto", maxWidth: 400, paddingRight: 5}, metacritic_searchcontainer);
  739. }
  740. };
  741. var cache = JSON.parse(GM_getValue("autosearchcache","{}"));
  742. for(var prop in cache) {
  743. // Delete cached values, that are older than 2 hours
  744. if((new Date()).getTime() - (new Date(cache[prop].time)).getTime() > 2*60*60*1000) {
  745. delete cache[prop];
  746. }
  747. }
  748. if(current.type == "music") {
  749. current.searchTerm = current.data[0];
  750. } else {
  751. current.searchTerm = current.data.join(" ");
  752. }
  753. if(current.searchTerm in cache) {
  754. handleresponse(cache[current.searchTerm], true);
  755. } else {
  756. GM_xmlhttpRequest({
  757. method: "POST",
  758. url: baseURL_autosearch,
  759. data: "search_term="+encodeURIComponent(current.searchTerm)+"&image_size=98&search_each=1&sort_type=popular",
  760. headers: {
  761. "Referer" : url,
  762. "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8",
  763. "Host" : "www.metacritic.com",
  764. "User-Agent" : "MetacriticUserscript Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0",
  765. "X-Requested-With" : "XMLHttpRequest"
  766. },
  767. onload: function(response) {
  768. response = {
  769. time : (new Date()).toJSON(),
  770. responseText : response.responseText,
  771. };
  772. cache[current.searchTerm] = response;
  773. GM_setValue("autosearchcache",JSON.stringify(cache));
  774. handleresponse(response, false);
  775. }
  776. });
  777. }
  778. });
  779. }
  780.  
  781. function metacritic_waitForHotkeys() {
  782. listenForHotkeys("meta",metacritic_searchcontainer);
  783. }
  784.  
  785. function metacritic_searchcontainer(ev, query) {
  786. if(!query) {
  787. if(current.type == "music") {
  788. query = current.data[0];
  789. } else {
  790. query = current.data.join(" ");
  791. }
  792. }
  793. $("#mcdiv123").remove();
  794. var div = $('<div id="mcdiv123"></div>').appendTo(document.body);
  795. div.css({
  796. position:"fixed",
  797. bottom :0,
  798. left: 0,
  799. minWidth: 300,
  800. maxHeight: "80%",
  801. maxWidth: 640,
  802. overflow:"auto",
  803. backgroundColor: "#fff",
  804. border: "2px solid #bbb",
  805. borderRadius:" 6px",
  806. boxShadow: "0 0 3px 3px rgba(100, 100, 100, 0.2)",
  807. color: "#000",
  808. padding:" 3px",
  809. zIndex: "5010001",
  810. });
  811. var query = $('<input type="text" size="60" id="mcisearchquery">').appendTo(div).focus().val(query).on('keypress', function(e) {
  812. var code = e.keyCode || e.which;
  813. if(code == 13) { // Enter key
  814. metacritic_search.call(this,e);
  815. }
  816. });
  817. $('<button id="mcisearchbutton">').text("Search").appendTo(div).click(metacritic_search);
  818. }
  819.  
  820.  
  821. function metacritic_search(ev, query) {
  822. if(!query) { // Use values from search form
  823. query = $("#mcisearchquery").val();
  824. }
  825. var type = searchType2metacritic(current.type);
  826.  
  827. var style = document.createElement('style');
  828. style.type = 'text/css';
  829. style.innerHTML = CSS;
  830. document.head.appendChild(style);
  831.  
  832. var div = $("#mcdiv123");
  833. var loader = $('<div style="width:20px; height:20px;" class="grespinner"></div>').appendTo($("#mcisearchbutton"));
  834. var url = baseURL_search.replace("{type}",encodeURIComponent(type)).replace("{query}",encodeURIComponent(query));
  835.  
  836. metacritic_searchResults(url,
  837. // On success
  838. function(results, time) {
  839. loader.remove();
  840. var accept = function(ev) {
  841. var a = $(this.parentNode).find("a[href*='metacritic.com']");
  842. var metaurl = a.attr("href");
  843. var docurl = document.location.href;
  844.  
  845. addToMap(docurl,metaurl);
  846. metacritic_showHoverInfo(metaurl);
  847. };
  848. var denyAll = function(ev) {
  849. var urls = [];
  850. var docurl = document.location.href;
  851. $("#mcdiv123searchresults").find("div.result a[href*='metacritic.com']").each(function() {
  852. addToBlacklist(docurl, this.href);
  853. });
  854. };
  855. var resultdiv = $("#mcdiv123searchresults").length?$("#mcdiv123searchresults").html(""):$('<div id="mcdiv123searchresults"></div>').css("max-width","95%").appendTo(div);
  856. results.forEach(function(html) {
  857. var singleresult = $('<div class="result"></div>').html(fixMetacriticURLs(html)+'<div style="clear:left"></div>').appendTo(resultdiv);
  858. $('<span title="Assist us: This is the correct entry!" style="cursor:pointer; color:green; font-size: 13px;">&check;</span>').prependTo(singleresult).click(accept);
  859. });
  860. var sub = $("<div></div>").appendTo(div);
  861. $('<time style="color:#b6b6b6; font-size: 11px;" datetime="'+time+'" title="'+time.toLocaleFormat()+'">'+minutesSince(time)+'</time>').appendTo(sub);
  862. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="'+url+'" title="Open Metacritic">'+decodeURI(url.replace("http://www.","@"))+'</a>').appendTo(sub);
  863. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px;">&#10062;</span>').appendTo(sub).click(function() {
  864. document.body.removeChild(this.parentNode.parentNode);
  865. });
  866. $('<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()});
  867. },
  868. // On error i.e. no results
  869. function(results, time) {
  870. loader.remove();
  871. var resultdiv = $("#mcdiv123searchresults").length?$("#mcdiv123searchresults").html(""):$('<div id="mcdiv123searchresults"></div>').appendTo(div);
  872. resultdiv.html("No search results.");
  873. var sub = $("<div></div>").appendTo(div);
  874. $('<time style="color:#b6b6b6; font-size: 11px;" datetime="'+time+'" title="'+time.toLocaleFormat()+'">'+minutesSince(time)+'</time>').appendTo(sub);
  875. $('<a style="color:#b6b6b6; font-size: 11px;" target="_blank" href="'+url+'" title="Open Metacritic">'+decodeURI(url.replace("http://www.","@"))+'</a>').appendTo(sub);
  876. $('<span title="Hide me" style="cursor:pointer; float:right; color:#b6b6b6; font-size: 11px;">&#10062;</span>').appendTo(sub).click(function() {
  877. document.body.removeChild(this.parentNode.parentNode);
  878. });
  879. }
  880. );
  881. }
  882.  
  883. var current = {
  884. url : null,
  885. type : null,
  886. data : null, // Array of raw search keys
  887. searchTerm : null
  888. };
  889.  
  890.  
  891. function showURL(url) {
  892. if(!isBlacklisted(url)) {
  893. var docurl = document.location.host.replace(/^www\./,"") + document.location.pathname + document.location.search;
  894. docurl = filterUniversalUrl(docurl);
  895. metacritic_showHoverInfo(url, docurl);
  896. } else {
  897. console.log(url +" is blacklisted!");
  898. }
  899. }
  900.  
  901.  
  902. var metacritic = {
  903. "mapped" : function metacritic_mapped(url, type) {
  904. // url was in the map/whitelist
  905. current.data = [url]
  906. current.url = url;
  907. current.type = type;
  908. current.searchTerm = url;
  909. showURL(url);
  910. },
  911. "music" : function metacritic_music(artistname, albumname) {
  912. current.data = [albumname.trim(),artistname.trim()]
  913. artistname = name2metacritic(artistname);
  914. albumname = albumname.replace("&"," ");
  915. albumname = name2metacritic(albumname);
  916. var url = baseURL_music + albumname + "/" + artistname;
  917. current.url = url;
  918. current.type = "music";
  919. current.searchTerm = albumname + "/" + artistname;
  920. showURL(url);
  921. },
  922. "movie" : function metacritic_movie(moviename) {
  923. current.data = [moviename.trim()]
  924. moviename = name2metacritic(moviename);
  925. var url = baseURL_movie + moviename;
  926. current.url = url;
  927. current.type = "movie";
  928. current.searchTerm = moviename;
  929. showURL(url);
  930. },
  931. "tv" : function metacritic_tv(seriesname) {
  932. current.data = [seriesname.trim()]
  933. seriesname = name2metacritic(seriesname);
  934. var url = baseURL_tv + seriesname;
  935. current.url = url;
  936. current.type = "tv";
  937. current.searchTerm = seriesname;
  938. showURL(url);
  939. },
  940. "pcgame" : function metacritic_pcgame(gamename) {
  941. current.data = [gamename.trim()]
  942. gamename = name2metacritic(gamename);
  943. var url = baseURL_pcgame + gamename;
  944. current.url = url;
  945. current.type = "pcgame";
  946. current.searchTerm = gamename;
  947. showURL(url);
  948. },
  949. "ps4game" : function metacritic_ps4game(gamename) {
  950. current.data = [gamename.trim()]
  951. gamename = name2metacritic(gamename);
  952. var url = baseURL_ps4 + gamename;
  953. current.url = url;
  954. current.type = "ps4game";
  955. current.searchTerm = gamename;
  956. showURL(url);
  957. },
  958. "xonegame" : function metacritic_xonegame(gamename) {
  959. current.data = [gamename.trim()]
  960. gamename = name2metacritic(gamename);
  961. var url = baseURL_xone + gamename;
  962. current.url = url;
  963. current.type = "xonegame";
  964. current.searchTerm = gamename;
  965. showURL(url);
  966. }
  967. };
  968.  
  969.  
  970. var Always = () => true;
  971. var sites = {
  972. 'bandcamp' : {
  973. host : ["bandcamp.com"],
  974. condition : function() {
  975. return unsafeWindow.TralbumData
  976. },
  977. products : [{
  978. condition : Always,
  979. type : "music",
  980. data : () => [unsafeWindow.TralbumData.artist, unsafeWindow.TralbumData.current.title]
  981. }]
  982. },
  983. 'itunes' : {
  984. host : ["itunes.apple.com"],
  985. condition : Always,
  986. products : [{
  987. condition : () => ~document.location.href.indexOf("/album/") ,
  988. type : "music",
  989. data : () => [document.querySelector("*[itemprop=byArtist]").textContent, document.querySelector("*[itemprop=name]").textContent]
  990. }]
  991. },
  992. 'googleplay' : {
  993. host : ["play.google.com"],
  994. condition : Always,
  995. products : [
  996. {
  997. condition : () => ~document.location.href.indexOf("/album/"),
  998. type : "music",
  999. data : () => [document.querySelector("*[itemprop=byArtist] a").textContent, document.querySelector("*[itemprop=name]").textContent]
  1000. },
  1001. {
  1002. condition : () => ~document.location.href.indexOf("/movies/details/"),
  1003. type : "movie",
  1004. data : () => document.querySelector("*[itemprop=name]").textContent
  1005. }
  1006. ]
  1007. },
  1008. 'imdb' : {
  1009. host : ["imdb.com"],
  1010. condition : Always,
  1011. products : [
  1012. {
  1013. condition : function() {
  1014. var e = document.querySelector("meta[property='og:type']");
  1015. if(e) {
  1016. return e.content == "video.movie"
  1017. }
  1018. return false;
  1019. },
  1020. type : "movie",
  1021. data : function() {
  1022. if(document.querySelector("h1[itemprop=name]")) { // Movie homepage (New design 2015-12)
  1023. return document.querySelector("h1[itemprop=name]").firstChild.textContent.trim();
  1024. } else if(document.querySelector("*[itemprop=name] a") && document.querySelector("*[itemprop=name] a").firstChild.data) { // Subpage of a move
  1025. return document.querySelector("*[itemprop=name] a").firstChild.data.trim();
  1026. } else if(document.querySelector(".title-extra[itemprop=name]")) { // Movie homepage: sub-/alternative-/original title
  1027. return document.querySelector(".title-extra[itemprop=name]").firstChild.textContent.replace(/\"/g,"").trim();
  1028. } else { // Movie homepage (old design)
  1029. return document.querySelector("*[itemprop=name]").firstChild.textContent.trim();
  1030. }
  1031. }
  1032. },
  1033. {
  1034. condition : function() {
  1035. var e = document.querySelector("meta[property='og:type']");
  1036. if(e) {
  1037. return e.content == "video.tv_show"
  1038. }
  1039. return false;
  1040. },
  1041. type : "tv",
  1042. data : () => document.querySelector("*[itemprop=name]").textContent
  1043. }
  1044. ]
  1045. },
  1046. 'steam' : {
  1047. host : ["store.steampowered.com"],
  1048. condition : () => document.querySelector("*[itemprop=name]"),
  1049. products : [{
  1050. condition : Always,
  1051. type : "pcgame",
  1052. data : () => document.querySelector("*[itemprop=name]").textContent
  1053. }]
  1054. },
  1055. 'tv.com' : {
  1056. host : ["www.tv.com"],
  1057. condition : () => document.querySelector("meta[property='og:type']"),
  1058. products : [{
  1059. condition : () => document.querySelector("meta[property='og:type']").content == "tv_show" && document.querySelector("h1[data-name]"),
  1060. type : "tv",
  1061. data : () => document.querySelector("h1[data-name]").dataset.name
  1062. }]
  1063. },
  1064. 'rottentomatoes' : {
  1065. host : ["www.rottentomatoes.com"],
  1066. condition : Always,
  1067. products : [{
  1068. condition : () => document.location.pathname.startsWith("/m/"),
  1069. type : "movie",
  1070. data : () => document.querySelector("h1").firstChild.textContent
  1071. },
  1072. {
  1073. condition : () => document.location.pathname.startsWith("/tv/") ,
  1074. type : "tv",
  1075. data : () => unsafeWindow.BK.TvSeriesTitle
  1076. }
  1077. ]
  1078. },
  1079. 'serienjunkies' : {
  1080. host : ["www.serienjunkies.de"],
  1081. condition : Always,
  1082. products : [{
  1083. condition : () => Always,
  1084. type : "tv",
  1085. data : function() {
  1086. if(document.querySelector("h1[itemprop=name]")) {
  1087. return document.querySelector("h1[itemprop=name]").textContent;
  1088. } else {
  1089. var n = $("a:contains(Details zur)");
  1090. if(n) {
  1091. var name = n.text().match(/Details zur Produktion der Serie (.+)/)[1];
  1092. return name;
  1093. }
  1094. }
  1095. }
  1096. }]
  1097. },
  1098. 'gamespot' : {
  1099. host : ["gamespot.com"],
  1100. condition : () => document.querySelector("[itemprop=device]"),
  1101. products : [
  1102. {
  1103. condition : () => ~$("[itemprop=device]").text().indexOf("PC"),
  1104. type : "pcgame",
  1105. data : () => document.querySelector("h1[itemprop=name]").textContent
  1106. },
  1107. {
  1108. condition : () => ~$("[itemprop=device]").text().indexOf("PS4"),
  1109. type : "ps4game",
  1110. data : () => document.querySelector("h1[itemprop=name]").textContent
  1111. },
  1112. {
  1113. condition : () => ~$("[itemprop=device]").text().indexOf("XONE"),
  1114. type : "xonegame",
  1115. data : () => document.querySelector("h1[itemprop=name]").textContent
  1116. }
  1117. ]
  1118. },
  1119. 'amazon' : {
  1120. host : ["amazon."],
  1121. condition : Always,
  1122. products : [
  1123. {
  1124. condition : function() {
  1125. var music = ["Music","Musique","Musik","Música","Musica","音楽"];
  1126. return music.some(function(s) {
  1127. if(~document.title.indexOf(s)) {
  1128. return true;
  1129. } else {
  1130. return false;
  1131. }
  1132. });
  1133. },
  1134. type : "music",
  1135. data : function() {
  1136. var artist = document.querySelector("#byline .author a").textContent;
  1137. var title = document.getElementById("productTitle").textContent;
  1138. title = title.replace(/\[([^\]]*)\]/g,""); // Remove [brackets] and their content
  1139. return [artist, title];
  1140. }
  1141. },
  1142. {
  1143. condition : () => (document.getElementById("aiv-content-title") && document.getElementsByClassName("season-single-dark").length),
  1144. type : "tv",
  1145. data : () => document.getElementById("aiv-content-title").firstChild.data.trim()
  1146. },
  1147. {
  1148. condition : () => document.getElementById("aiv-content-title"),
  1149. type : "movie",
  1150. data : () => document.getElementById("aiv-content-title").firstChild.data.trim()
  1151. }
  1152. ]
  1153. },
  1154. 'BoxOfficeMojo' : {
  1155. host : ["boxofficemojo.com"],
  1156. condition : () => ~document.location.search.indexOf("id="),
  1157. products : [{
  1158. condition : () => document.querySelector("#body table:nth-child(2) tr:first-child b"),
  1159. type : "movie",
  1160. data : () => document.querySelector("#body table:nth-child(2) tr:first-child b").firstChild.data
  1161. }]
  1162. },
  1163. 'AllMovie' : {
  1164. host : ["allmovie.com"],
  1165. condition : () => document.querySelector("h2[itemprop=name].movie-title"),
  1166. products : [{
  1167. condition : () => document.querySelector("h2[itemprop=name].movie-title"),
  1168. type : "movie",
  1169. data : () => document.querySelector("h2[itemprop=name].movie-title").firstChild.data.trim()
  1170. }]
  1171. },
  1172. 'en.wikipedia' : {
  1173. host : ["en.wikipedia.org"],
  1174. condition : Always,
  1175. products : [{
  1176. condition : function() {
  1177. if(!document.querySelector(".infobox .summary")) {
  1178. return false;
  1179. }
  1180. var r = /\d\d\d\d films/;
  1181. return $("#catlinks a").filter((i,e) => e.firstChild.data.match(r)).length;
  1182. },
  1183. type : "movie",
  1184. data : () => document.querySelector(".infobox .summary").firstChild.data
  1185. },
  1186. {
  1187. condition : function() {
  1188. if(!document.querySelector(".infobox .summary")) {
  1189. return false;
  1190. }
  1191. var r = /television series/;
  1192. return $("#catlinks a").filter((i,e) => e.firstChild.data.match(r)).length;
  1193. },
  1194. type : "tv",
  1195. data : () => document.querySelector(".infobox .summary").firstChild.data
  1196. }]
  1197. },
  1198. 'movies.com' : {
  1199. host : ["movies.com"],
  1200. condition : () => document.querySelector("meta[property='og:title']"),
  1201. products : [{
  1202. condition : Always,
  1203. type : "movie",
  1204. data : () => document.querySelector("meta[property='og:title']").content
  1205. }]
  1206. },
  1207. 'themoviedb' : {
  1208. host : ["themoviedb.org"],
  1209. condition : () => document.querySelector("meta[property='og:type']"),
  1210. products : [{
  1211. condition : () => document.querySelector("meta[property='og:type']").content == "movie",
  1212. type : "movie",
  1213. data : () => document.querySelector("meta[property='og:title']").content
  1214. },
  1215. {
  1216. condition : () => document.querySelector("meta[property='og:type']").content == "tv_series",
  1217. type : "tv",
  1218. data : () => document.querySelector("meta[property='og:title']").content
  1219. }]
  1220. },
  1221. 'letterboxd' : {
  1222. host : ["letterboxd.com"],
  1223. condition : () => unsafeWindow.filmData && "name" in unsafeWindow.filmData,
  1224. products : [{
  1225. condition : Always,
  1226. type : "movie",
  1227. data : () => unsafeWindow.filmData.name
  1228. }]
  1229. },
  1230. 'TVmaze' : {
  1231. host : ["tvmaze.com"],
  1232. condition : () => document.querySelector("h1"),
  1233. products : [{
  1234. condition : Always,
  1235. type : "tv",
  1236. data : () => document.querySelector("h1").firstChild.data
  1237. }]
  1238. },
  1239. 'TVGuide' : {
  1240. host : ["tvguide.com"],
  1241. condition : Always,
  1242. products : [{
  1243. condition : () => document.location.pathname.startsWith("/tvshows/"),
  1244. type : "tv",
  1245. data : () => document.querySelector("meta[property='og:title']").content
  1246. }]
  1247. },
  1248. 'followshows' : {
  1249. host : ["followshows.com"],
  1250. condition : Always,
  1251. products : [{
  1252. condition : () => document.querySelector("meta[property='og:type']").content == "video.tv_show",
  1253. type : "tv",
  1254. data : () => document.querySelector("meta[property='og:title']").content
  1255. }]
  1256. },
  1257. 'TheTVDB' : {
  1258. host : ["thetvdb.com"],
  1259. condition : Always,
  1260. products : [{
  1261. condition : () => ~document.location.search.indexOf("tab=series"),
  1262. type : "tv",
  1263. data : () => document.querySelector("#content h1").firstChild.data
  1264. }]
  1265. },
  1266. 'ConsequenceOfSound' : {
  1267. host : ["consequenceofsound.net"],
  1268. condition : () => document.querySelector("meta[property='og:title']"),
  1269. products : [{
  1270. condition : () => document.querySelector("meta[property='og:title']").content.match(/.+: (.+) [-–] (.+)/),
  1271. type : "music",
  1272. data : function() {
  1273. var m = document.querySelector("meta[property='og:title']").content.match(/.+: (.+) [-–] (.+)/);
  1274. m.shift();
  1275. return m;
  1276. }
  1277. }]
  1278. },
  1279. 'Pitchfork' : {
  1280. host : ["pitchfork.com"],
  1281. condition : () => ~document.location.href.indexOf("/reviews/albums/"),
  1282. products : [{
  1283. condition : () => document.querySelector(".review-article .tombstone .score"),
  1284. type : "music",
  1285. data : function() {
  1286. var artist = document.querySelector(".review-article .tombstone h2.artists").innerText.trim();
  1287. var album = document.querySelector(".review-article .tombstone h1.review-title").innerText.trim();
  1288. return [artist, album];
  1289. }
  1290. }]
  1291. },
  1292. 'Last.fm' : {
  1293. host : ["last.fm"],
  1294. condition : () => document.querySelector("*[data-page-resource-type]") && document.querySelector("*[data-page-resource-type]").dataset.pageResourceType == "album",
  1295. products : [{
  1296. condition : () => document.querySelector("*[data-page-resource-type]").dataset.pageResourceName,
  1297. type : "music",
  1298. data : function() {
  1299. var artist = document.querySelector("*[data-page-resource-type]").dataset.pageResourceArtistName;
  1300. var album = document.querySelector("*[data-page-resource-type]").dataset.pageResourceName;
  1301. return [artist, album];
  1302. }
  1303. }]
  1304. },
  1305. 'TVRage' : {
  1306. host : ["tvrage.com"],
  1307. condition : () => document.querySelector(".content_title"),
  1308. products : [{
  1309. condition : Always,
  1310. type : "tv",
  1311. data : () => document.querySelector(".content_title").textContent
  1312. }]
  1313. },
  1314. 'rateyourmusic' : {
  1315. host : ["rateyourmusic.com"],
  1316. condition : () => document.querySelector("meta[property='og:type']"),
  1317. products : [{
  1318. condition : () => document.querySelector("meta[property='og:type']").content == "music.album",
  1319. type : "music",
  1320. data : function() {
  1321. var artist = document.querySelector(".section_main_info .artist").innerText.trim();
  1322. var album = document.querySelector(".section_main_info .album_title").innerText.trim();
  1323. return [artist, album];
  1324. }
  1325. }]
  1326. },
  1327. 'spotify_webplayer' : {
  1328. host : ["open.spotify.com"],
  1329. condition : () => Always,
  1330. products : [{
  1331. condition : () => document.querySelector("#main .main-view-container .content.album"),
  1332. type : "music",
  1333. data : function() {
  1334. var artist = document.querySelector("#main .media-bd div a[href*='artist']").textContent;
  1335. var album = document.querySelector("#main .media-bd h2").textContent;
  1336. return [artist, album];
  1337. }
  1338. },
  1339. {
  1340. condition : () => document.location.pathname.startsWith("/album/") && document.querySelector("meta[property='og:type']").content == "music.album",
  1341. type : "music",
  1342. data : function() {
  1343. var artist = "";
  1344. var album = document.querySelector("meta[property='og:title']").content;
  1345. return [artist, album];
  1346. }
  1347. }]
  1348. },
  1349. 'spotify' : {
  1350. host : ["play.spotify.com"],
  1351. condition : () => Always,
  1352. products : [{
  1353. condition : () => document.location.pathname.startsWith("/album/"),
  1354. type : "music",
  1355. data : function() {
  1356. var artist = document.querySelector(".context_landing p.secondary-title").textContent;
  1357. var album = document.querySelector(".context_landing p.primary-title").textContent;
  1358. return [artist, album];
  1359. }
  1360. }]
  1361. },
  1362. };
  1363.  
  1364.  
  1365. function main() {
  1366.  
  1367. var map = false;
  1368.  
  1369. for(var name in sites) {
  1370. var site = sites[name];
  1371. if(site.host.some(function(e) {return ~this.indexOf(e)}, document.location.hostname))
  1372. if(site.host.some(function(e) {return ~this.indexOf(e)}, document.location.hostname) && site.condition()) {
  1373. for(var i = 0; i < site.products.length; i++) {
  1374. if(site.products[i].condition()) {
  1375. // Check map for a match
  1376. if(map === false) {
  1377. map = JSON.parse(GM_getValue("map","{}"));
  1378. }
  1379. var docurl = document.location.host.replace(/^www\./,"") + document.location.pathname + document.location.search;
  1380. docurl = filterUniversalUrl(docurl);
  1381. if(docurl in map) {
  1382. // Found in map, show result
  1383. var metaurl = map[docurl];
  1384. metacritic["mapped"].apply(undefined, [baseURL + metaurl, site.products[i].type]);
  1385. break;
  1386. }
  1387. // Try to retrieve item name from page
  1388. var data;
  1389. try {
  1390. data = site.products[i].data();
  1391. } catch(e) {
  1392. data = false;
  1393. console.log(e);
  1394. }
  1395. if(data) {
  1396. metacritic[site.products[i].type].apply(undefined, Array.isArray(data)?data:[data]);
  1397. }
  1398. break;
  1399. }
  1400. }
  1401. break;
  1402. }
  1403. }
  1404. }
  1405.  
  1406.  
  1407.  
  1408.  
  1409.  
  1410. main();
  1411. var lastLoc = document.location.href;
  1412. var lastContent = document.body.innerText;
  1413. var lastCounter = 0;
  1414. function newpage() {
  1415. if(lastContent == document.body.innerText && lastCounter < 15) {
  1416. window.setTimeout(newpage, 500);
  1417. lastCounter++;
  1418. } else {
  1419. lastCounter = 0;
  1420. main();
  1421. }
  1422. }
  1423. window.setInterval(function() {
  1424. if(document.location.href != lastLoc) {
  1425. lastLoc = document.location.href;
  1426. $("#mcdiv123").remove();
  1427. window.setTimeout(newpage,1000);
  1428. }
  1429. },500);
  1430.