Ghost: inline script in the editor has problems with ==

Put this in the editor (Ghost v0.6.4)

<script>
var x = 0;
if ( x === 0 ) {
    alert("yay");
}
</script>

then publish.

View the blog post in a web browser. Would expect an alert box saying ‘yay’. However, we get a javascript error.

Inspecting the rendered HTML/JS code and we see

<script>
var x = 0;
if ( x <mark>= 0 ) {
    alert("yay");
}
</script>

It looks like some macro replacement magic is taking place, replacing any == characters with <mark>.

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 2
  • Comments: 17 (5 by maintainers)

Most upvoted comments

I have the same issue on Ghost Pro, the only way to avoid the problem is to add <pre> tags before and after the <script> tags.

@intositeme The work around I’m using is to modify showdown-ghost v0.3.6 to escape <script> blocks before applying highlighting. Assuming you are using Ghost v0.7.6 simply replace node_modules\showdown-ghost\src\extensions\highlight.js with the following and restart Ghost:

/* jshint node:true, browser:true, -W044 */

// Adds highlight syntax as per RedCarpet:
//
// https://github.com/vmg/redcarpet
//
// This is ==highlighted==. It looks like this: <mark>highlighted</mark>

(function () {
    var highlight = function () {
        return [
            {
                type: 'html',
                filter: function (text) {
                    var highlightRegex = /(=){2}([\s\S]+?)(=){2}/gim,
                        extractions = {},
                        hashID = 0;

                    function hashId() {
                        return hashID += 1;
                    }

                    // Extract pre|code|script blocks
                    text = text.replace(/<(pre|code|script)>[\s\S]*?<\/(\1)>/gim, function (x) {
                        var hash = hashId();
                        extractions[hash] = x;
                        return '{gfm-js-extract-' + hash + '}';
                    }, 'm');

                    text = text.replace(highlightRegex, function (match, n, content) {
                        // Check the content isn't just an `=`
                        if (!/^=+$/.test(content)) {
                            return '<mark>' + content + '</mark>';
                        }

                        return match;
                    });

                    // Replace extractions
                    text = text.replace(/\{gfm-js-extract-([0-9]+)\}/gm, function (x, y) {
                        return extractions[y];
                    });

                    return text;
                }
            }
        ];
    };

    // Client-side export
    if (typeof window !== 'undefined' && window.Showdown && window.Showdown.extensions) {
        window.Showdown.extensions.highlight = highlight;
    }
    // Server-side export
    if (typeof module !== 'undefined') {
        module.exports = highlight;
    }
}());