Search code examples
javascriptcssgoogle-chromefirefoxbrowser-addons

Browser render hook


Do browsers provide any pre-render hook where you can apply changes to styles of DOM elements before they are rendered?

For example, I might want to change the color of anything that is red to green

This requirement is for a browser extension so the solution should work across different webpages. It is not trivial to override the style of an element while being agnostic of the source code as the style of an element is a result of the CSS and Javascript that runs on it and the mechanism is different for different websites. Ways that come to mind are:

  • Parsing the CSS and Javascript of the web page to determine the styles of elements. This seems redundant as the browser is also doing it
  • Scanning the DOM and checking the computed styles of each element and overriding stuff. This works but if elements change dynamically, we have to repeatedly scan for changes which might be heavy

So does such a browser hook exist? If not, what alternate approach would you recommend?


Solution

  • For the kind of thing you are trying to achieve, it would be very helpful for you to look at the code of a Chrome extension called Dark Reader. This extension can turn your entire page dark but does so intelligently by analysing the css of the code. If something is already dark, it leaves it as it is. Backgrounds that are bright are made black and text is made white only if the contrast is necessary. An image would make things clear

    Original Original

    Dark reader rendered enter image description here

    Dark reader uses js to analyze the css and styles and injects its own CSS styles in the page to get the required effect.

    If you really want to tap into the render pipeline of the browser, then have a look at Project Houdini that will allow such customizations to the browser in the future. Its not ready now.