How to syntax highlight JSON inside a HTML page on the client side?

Issue

I am using a HTML documentation page by an external service which renders JSON snippets within an HTML page.
The HTML source code looks like this:

<pre>{
    "product-link": "https://example.com/product-link",
    "teaser_image": "https://example.com/teaser-image",
    "product_image_first": "https://example.com/product-image-first",
    "headline": "Example headline",
}</pre>

The JSON block renders without syntax highlighting.
Since I am not in control of the external service I would like to apply syntax highlighting (color) to the JSON snippet via user script.

I found Greasemonkey but still missing the point on how to inject a syntax highlighter library.

Solution

Thanks to xander here is the first working version of my user script base on code-prettify:

(function(d) {

  stylizePreElements = function() {
    var preElements = document.getElementsByTagName("pre");
    for (i = 0; i < preElements.length; ++i) {
      var preElement = preElements[i];
      preElement.className += "prettyprint";
    }
  };

  injectPrettifyScript = function() {
    var scriptElement = document.createElement('script');
    scriptElement.setAttribute("src", "https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js");
    document.head.appendChild(scriptElement);
  };

  stylizePreElements();
  injectPrettifyScript();

})(document)

Thank you for making my day nicer!

Answered By – JJD

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.