Previewing HTML files directly on GitHub with a bookmarklet
Published on in Bookmarklets and JavaScript
There's no built-in way to preview HTML files on GitHub, but you can use this nifty bookmarklet. (GitHub's project managers HATE it!)
-
Create a bookmark with this "URL":
javascript: (() => { const selector = '#read-only-cursor-text-area'; const html = document.querySelector(selector)?.value; if (!html) { return alert(`Error: element ${selector} not found`); } document.open(); document.write(html); document.close(); })();
-
Open an HTML file on GitHub.
-
Run the bookmarklet by "opening" the bookmark. It replaces the current page's contents with the HTML file's contents.
Works great with self-contained / zero-dependency HTML files generated with SingleFile.
Notes:
- The bookmarklet breaks GitHub's client-side routing, so navigating back with the browser's Back button doesn't work. Reloading the page (F5) fixes the issue.
- The bookmarklet doesn't work on raw.githubusercontent.com because of a strict Content Security Policy (CSP). (Plus the bookmarklet is looking for an element that's not present on this domain.)
- The CSP used on github.com can also be too strict; in such cases, I would personally try an alternative solution on Stack Overflow by ostrokach.
- The bookmarklet is brittle, i.e. it might need tweaking from time to time as GitHub gets updated.
Alternative bookmarklet code that retains the page's header and footer, so that running the bookmarklet doesn't break client-side routing:
javascript: (() => {
const selector = '#read-only-cursor-text-area';
const html = document.querySelector(selector)?.value;
if (!html) {
return alert(`Error: element ${selector} not found`);
}
const $iframe = document.createElement('iframe');
$iframe.style.height = '100vh';
$iframe.style.width = '100%';
$iframe.srcdoc = html;
document.querySelector('turbo-frame').replaceChildren($iframe);
$iframe.scrollIntoView();
})();
The CSP on github.com blocks the iframe from loading most links, so with this version most links are effectively disabled (i.e. clicking a link doesn't do anything, at least on Firefox). In my case this is a feature, not a bug.
There are (at least) two relevant questions on Stack Overflow:
- How to see an HTML page on GitHub as a normal rendered HTML page to see preview in browser, without downloading?
- Can I run HTML files directly from GitHub, instead of just viewing their source?
Neither question has as nice solutions as this one by me (until now). Bookmarklets are underrated!