Search code examples
javascriptcssreadability

Injecting CSS into a website


I'm creating a browser extension that'll allow you to adjust the CSS of a page.
Basically, if the user decides on a dark background with light text then that change should reflect across the site that they are viewing.
The reason for this is readability.
People with colour blindness and some vision related disabilities find it difficult to read some colours.

There are several challenges with this.
I want to be able to change background-color elements to the chosen background colour and the color element to the chosen text-colour.

Obviously I have to account for complicated website layouts, and cater for those rules that are complicated, i.e.

#container div.note p

I can use Javascript in this, but no libraries like JQuery, so is there a way I can do this?

Is there a way I can apply a CSS Stylesheet to the page that will override every background element and every color element in their stylesheet?


Solution

  • I suggest writing a GreaseMonkey script for this since it will allow you to set a rule to run on every page of a site. GM is just a wrapper for JavaScript (although it does extend the functionality as well).

    And no, it wouldn't be hard to write a script that applies a CSS stylesheet. Just create a <link> element linking to it. Alternatively you could hard-code the style in and create a <style> object on the page.

    Take a look at this article: Dynamically loading external JavaScript and CSS files

    function loadcssfile(filename){
      var fileref=document.createElement("link")
      fileref.setAttribute("rel", "stylesheet")
      fileref.setAttribute("type", "text/css")
      fileref.setAttribute("href", filename)
    
     if (typeof fileref!="undefined")
      document.getElementsByTagName("head")[0].appendChild(fileref)
    }
    
    loadcssfile("mystyle.css") ////dynamically load and add this .css file