XKCD -- Easy Random

Quicker and more reliable "random comic" button

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。

您需要先安装用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name     XKCD -- Easy Random
// @description Quicker and more reliable "random comic" button
// @license MIT
// @version  1
// @namespace https://keybase.io/jpaugh
// @support  Chat with me on Keybase
// @author   Jonathan Paugh
// @grant    none
// @match 	 https://xkcd.com/*
// @compatible firefox
// @compatible chrome
// @compatible IE11 --- not that it helps
// ==/UserScript==

var MAGICAL_BG_COLOR = "orangered"
var XKCDS_WHEN_CHECKED = 2134
var XKCD_CHECK_DATE = new Date(2019, 4, 9)
var COMICS_PER_WEEK = 3

function guestimateCurrentCount() {
  var now = new Date()
  var MILLI_PER_WEEK = 7 * 24 * 60 * 60 * 1000
  var weeksSinceChecked = (now.getTime() - XKCD_CHECK_DATE.getTime()) / MILLI_PER_WEEK
  return XKCDS_WHEN_CHECKED + Math.floor(weeksSinceChecked * COMICS_PER_WEEK) // Works for past and future dates! :-D
}

function getRandomComicInclusive(min, max) {
  min = Math.ceil(min) // Why did you give me a fractional min? You sneaky caller!
  max = Math.floor(max)
  return Math.floor(Math.random() * (max - min + 1)) + min
}

var min = 1
var max = guestimateCurrentCount()
// TODO: Add a fudge factor (+20) to the max, and then pre-load the new comic to ensure it exists.
// Maybe I should load it via AJAX and overwrite the current page? IDK

var randLinks = document.querySelectorAll("a[href^='//c.xkcd.com/random/comic']")
Array.prototype.forEach.call(randLinks, function (el) {
  el.style.backgroundColor = MAGICAL_BG_COLOR
  el.addEventListener("click", function (event) {
    (event.preventDefault)
      ? event.preventDefault()
      : (event.returnValue = false)
    window.location.href = "https://xkcd.com/" + getRandomComicInclusive(min, max)
  })
});