Simple hacky dark mode for any site

As I type now, I am sleepy an in a dark room with my laptop. It hurts my eyes looking at most websites with white backgrounds and dark text. So, I thus present to you a bookmarklet that will hack a dark mode for the page at the click of said bookmarklet button.

This has several flaws, the biggest one perhaps being that background images will appear color-inverted, but hey, if you are working at 2am in the dark, why not have some weird colors jumping out at you?

Here is the super simple JavaScript code I used

var newScript = document.createElement('style');
var content = document.createTextNode('html{filter: invert(100%); html img{filter: invert(1) hue-rotate(180deg);}');
newScript.appendChild(content);
var head = document.getElementsByTagName('head')[0];
head.appendChild(newScript);

Pretty basic.

Now we url-safe-ify it:

javascript:(function()%7Bvar%20newScript%20%3D%20document.createElement('style')%3B%0Avar%20content%20%3D%20document.createTextNode('html%7Bfilter%3A%20invert(100%25)%3B%20html%20img%7Bfilter%3A%20invert(1)%20hue-rotate(180deg)%3B%7D')%3B%0AnewScript.appendChild(content)%3B%0Avar%20head%20%3D%20document.getElementsByTagName('head')%5B0%5D%3B%0Ahead.appendChild(newScript)%3B%7D)()%3B

This code can now be used as a bookmark “URL” in your browser. When you click that bookmark, your webpage will automagically get dark-mode-ified.

To try it out, drag this link to your bookmark bar.