ReadabilityJS - adding Reader View Mode to websites
January 17, 2021
One of the features I absolutely love in Firefox is Firefox Reader View. This removes all the clutter and present the content in text format for better readability and relief for eyes(It also removes the ad banners 😉 ).
Not all the browsers (Chrome needs special flag to enable this 😐 ) have a readability mode thus, providing an option for reader mode within your website would be a huge help to your users and would make your webpage more accessible.
The good news is you do not have to implement this on your own, Mozilla has a standalone version of the readability library used for Firefox Reader View - Readability.js.
The usage is pretty simple and straight forward:
-
We need to include the readability.js in our code in either of 2 ways:
- Download the file via https://github.com/mozilla/readability/releases
- Install npm package - https://www.npmjs.com/package/@mozilla/readability
-
Create a new
Readabiltyobject from DOM document nodeconst article = new Readability(document).parse();This article object will have following properties
title: article titlecontent: HTML string of processed article contenttextContent: text content of the article (all HTML removed)length: length of an article, in charactersexcerpt: article description, or short excerpt from the contentbyline: author metadatadir: content direction (LTR or RTL)
Note Readability morphs the actual object so better to pass a clone node.
const documentClone = document.cloneNode(true); const article = new Readability(documentClone).parse(); -
Substitute this
article.textContentin the desired div and done 😎
See this in action here - https://itsopensource.com/demos/readability
Reference: https://github.com/mozilla/readability