[SalesForce] Javascript variable – Uncaught SyntaxError: Invalid or unexpected token

I want to create a text file with a chat transcript in a post-chat page (Visualforce page).

I have tried to assign the transcript using Javascript to a variable:

var temptranscript="{!$CurrentPage.parameters.transcript}";

But I get an error: "Uncaught SyntaxError: Invalid or unexpected token".

Using the 'inspect element' in Chrome, you can see that the transcript value renders to:

var temptranscript="bob S (2:00:59 PM):Greetings 
visitor (2:01:05 PM):hello bob
bob S (2:01:36 PM):how may I help
";

it seems that because of the 'break lines', it fails to detect the whole transcript as a string so it only detects the first row and throws this error.

My question is, how can I manipulate the transcript if I cannot assign it to a variable?

  (function() {
        var textFile = null,
            makeTextFile = function(text) {
                var data = new Blob([text], {
                    type: 'text/plain'
                });
                if (textFile !== null) {
                    window.URL.revokeObjectURL(textFile);
                }
                textFile = window.URL.createObjectURL(data);
                return textFile;
            };
        var temptranscript="{!$CurrentPage.parameters.transcript}";;
        var link = document.getElementById('downloadlink');
        link.href = makeTextFile(temptranscript);
    })();

Best Answer

You should be able to use JSENCODE to transform the text into a JavaScript-safe string:

    var temptranscript="{!JSENCODE($CurrentPage.parameters.transcript)}";

You should always use this formula when using any variable that can be manipulated by a user; your original code is actually a XSS (Cross-Site Scripting) vulnerability, because it would allow arbitrary JavaScript code to be executed.

Related Topic