Sending Javascript code to client-side is not escaped correctly

332 views Asked by At

I'm struggling with an encoding-problem in a small system I'm constructing.

In an HTML, this script is loaded

<script src="http://localhost:8000/serving/dk-711218"></script> 

and normally I can't access the HTML so everything has to be done inside the javascript file.

The server-side scripts are made in Node.js and it returns pieces of code depending on some settings in customizable XML files. For instance, when displaying an image the system returns a simple

<img src="mypicture.jpg" />

and if it's a text, it returns

<div class="myClass">This is a test</div>

and if they have special behaviors, this code is included as well.

These parts work as intended. These chunks of code resides inside a number of classes and are returned as needed so that the code is gradually built.

So far, so good.

The problem is returning the SWFobject library code, because it seems to corrupt the code on the fly.

All code has been escaped and encoded with encodeURIComponent so that the system just needs to decode and unescape. But the validation fails.

Here's an example of the first few lines before encoding/escaping:

var%2520swfobject%253Dfunction%2528%2529%257Bvar...

Here's how a piece of the SWFObject looks like in the Firefox source code window when accessing the page:

and here's how a piece of the decoded SWFObject looks like in the same window:

This occurs at several places and something that's common for these occurrences is that it looks like the less-than character for unknown reasons is interpreted differently.

Here's the view renderer and I can't figure out if problem is caused in the code or when rendering the code.

Any ideas to what's causing this behavior? Or perhaps some advices on best practice when including code this way?


Responses to comments:

try JSON.stringify

I've tried the JSON solution out as well and it does the trick! What I did was - as before - to pre-process the included code, using a little tool I built with two input-fields and a JSON.stringify-command between the two. This resulted in the content of returnvar:

Module.prototype.opens = function () {
    var returnvar = "var swfobject=function(){var D=\"undefined\",r=\"object\",S=\"Shockwave Flash\",W=\"ShockwaveFlash.ShockwaveFlash\",q=\"application/x-shockwave-flash\",R=\"SWFObjectExprInst\"... etc. 

and a JSON.parse is used to correct it again in the renderer:

router.get('/serving/:id', function (req, res) {
    var readSymbolicsXMLCallback = function(data) {
        res.render('index', {
            id: req.params.id,
            embedcode: JSON.parse(data)
        });
    }
    var embedcode = readSymbolicsXML(req.params.id, readSymbolicsXMLCallback);
});
0

There are 0 answers