Currently reading: Stories of Your Life and Others by Ted Chiang

Dark mode for PDFs in Firefox

Firefox is unique in its handling of PDF files: it uses an open-source JavaScript-based viewer. This gives you a little more access to modify how a PDF is displayed than you'll get out of other browsers.

Due to security concerns, however, your browser extensions that inject stuff into the current page aren't allowed to operate on certain types of URLs like those of local files or the new-tab page. You'll know that's the case because your extensions' icons will be grayed out and/or display some kind of message about how they're not allowed to run in the current context.

This all means my beloved Stylus can't be used to make blindingly white PDFs ⸺ and they're all blindingly white, aren't they? ⸺ more comfortable to read. Hope is not lost, however, as you can still access the web console. Open it with F12 and then switch to the console tab. Therein you can run this code to turn a harsh black-on-white PDF into a dim-yellowish-on-brown setup instead:

const el = typeof viewer !== 'undefined' ? viewer : document.body;

el.style.filter = 'grayscale(1) invert(1) sepia(0.69) contrast(69%)';
el.style.background = '#e3e4dd';

Modify the numbers as you see fit. You could for instance remove the sepia() filter and increase the contrast to put it closer to a standard white-on-black setup. The filter setup above produces an end result as follows:

This used to be black text on a white background!

Yes, images get whacked by this color inversion too, but I don't think there's anything that can be done about it. Were they actual <img> tags within the document then they could be inverted again back to normal (though still made sepia), but they're instead handled via the Canvas API and thus can't be meddled with.

If you're a big PDF reader, you can create a bookmarklet out of that code above by reducing it down to a single line, wrapping it in an IIFE, and adding javascript: to the front of it. Every time you pull up a PDF that's blinding you, click the bookmarklet to execute the code and make it readable.

javascript:(function () { const el = typeof viewer !== 'undefined' ? viewer : document.body; el.style.filter = 'grayscale(1) invert(1) sepia(0.69) contrast(69%)'; el.style.background = '#e3e4dd';})();

Give this bookmarklet a keyword in the bookmarks manager and you can get to it even easier. If "pdf" is that keyword:

  • Open some PDF file.
  • Hit Cmd-L or F6 to select the address bar.
  • Type "pdf" to bring up the bookmarklet.
  • Hit enter to run it.
  • Read in dim, comfortable peace.

This code does not work in Chromium-based browsers nor (presumably; I haven't checked yet) in Safari as they use an entirely different method for PDF display. Running the code anyway results in a blank <body> tag with a #e3e4dd background.

Leave a comment

Your email address will not be published. Required fields are marked *