Skip to content

Switching to syntax highlighting with Prism

I use the beautyofcode extension for most of my code examples. It provides two possible syntax highlighting plugins: Syntax Highlighter and Prism. Back then I picked the first option.

But while I implemented a solid Content Security Policy (CSP) on this website, I came across the following issue: Syntax Highlighter was no longer useable with it.

If you want to prevent Cross-site scripting (XSS) on your website, you have to add the CSP directive script-src (or default-src) and you mustn't use the options 'unsafe-inline' and 'unsafe-eval'.

The problem was: Syntax Highlighter uses the JavaScript eval() function. This is considered a potential XSS gateway as it evaluates a string as a JavaScript expression. Therefore it is blocked by CSP when 'unsafe-eval' is missing.

A quick check showed: Prism has no issues with CSP. And as Prism is also supported by EXT:beautyofcode, switching was not causing any headache.

I adjusted the TypoScript configuration and downloaded the current Prism JavaScript and stylesheet from the official website. Or rather found a custom Monokai theme which I extended later.
EXT:beautyofcode does provide all necessary files for both plugins, but I had removed them (by customizing the templates) in favor of an own implementation.
The new Prism JavaScript got appended to my footer.js. I added the Prism stylesheet to my SCSS files and adjusted it after my fancy.

Since I was working on this topic, I also implemented syntax highlighting directly in CKEditor. Thomas Kieslich shows you how it works on his blog (german).

With the CKEditor plugin "codesnippet" you can already use Prism. If you need line highlighting or line numbers, you could extend this plugin with another one https://ckeditor.com/cke4/addon/prism. I didn't go the extra mile for now. If I find the time later, I could even replace EXT:beautyofcode with this.

Further advantages:

  • Syntax Highlighter had a plaintext mode to copy the code, which could cause issues with whitespace in Chrome. With Prism, you can easily copy the code.
  • For some reason, Syntax Highlighter stopped working if I installed EXT:min to minify the HTML. No problem with Prism.
Back

I'm Sebastian Klein, web developer with a focus on TYPO3 CMS. These pages want to provide you with assistance and informations about TYPO3 and web development in general.