Stack Exchange sites support hiding text as a spoiler with >!
; for example:
This text will be hidden until you hover over it/tap the "show spoiler" button.
This gets a lot of use on the Sci-Fi & Fantasy stack, usually to cover up key plot elements of a particular work (like the recent Star Wars film).
That’s a good way to avoid spoilers if you haven’t seen the work in question, but it can be annoying if you already know the plot. Over on Meta SFF, somebody asked whether it would be possible to unhide spoilers on questions with particular tags.
I wrote this UserScript, which allows the user to specify an array of tags, and will unhide spoilers on questions with those tags:
// ==UserScript==
// @name SFF.SE Show spoilers on questions with particular tags
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Show all spoilers on SFF.SE questions with specified tags
// @author alexwlchan
// @match *://scifi.stackexchange.com/questions/*
// @match *://meta.scifi.stackexchange.com/questions/*
// @grant none
// ==/UserScript==
/* jshint -W097 */
'use strict';
// If every tag on a question is in this array, then the spoilers on this
// question will be shown.
var SHOW_ME_SPOILERS_IF_TAGGED = [
"harry-p0tter",
"star-w4rs",
];
// Returns an array of tags on a question
var getTagsOnQuestion = function() {
var taglist = document.getElementsByClassName("post-taglist")[0];
var hrefs = taglist.getElementsByClassName("post-tag");
var tags = [];
for (var ii = 0; ii < hrefs.length; ii++) {
tags.push(hrefs[ii].innerText);
}
return tags;
}
// Returns true/false depending on whether the spoilers on this question
// should be shown -- that is, whether every tag on the question is in
// SHOW_ME_SPOILERS_IF_TAGGED.
var shouldShowSpoilersOnQuestion = function() {
// Get the tags on a question. All questions have at least one tag.
var tags = getTagsOnQuestion();
for (var jj = 0; jj < tags.length; jj++) {
// If we don't find the tag in the array of spoiler-able tags,
// then we have to reject the question.
if (SHOW_ME_SPOILERS_IF_TAGGED.indexOf(tags[jj]) == -1) {
return false;
}
}
return true;
}
// Modify all the spoilers on the page to show their spoiler text
var showSpoilers = function() {
var spoilers = document.getElementsByClassName("spoiler");
for (var kk = 0; kk < spoilers.length; kk++) {
spoilers[kk].transition = "none";
spoilers[kk].style.color = "#222426";
}
}
if (shouldShowSpoilersOnQuestion()) {
showSpoilers();
}
Any feedback is welcome, but particularly:
- Is this good/idiomatic JavaScript?
- Is the intent of the code clear?
- Are there any edge cases that I’ve missed?
- Is there a better way to check if (tags on the question) is a subset of (tags the user wants spoilers to be shown for)? I feel like my current approach is quite inefficient.