Passing server data to client script with Content Security Policy

Viewed 1146

With the Content Security Policy header set on a web server (https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), any inline script is blocked by modern browsers. It is recommended to place all javascript in .js files and configure the policy to authorize the domain where these .js files are hosted.

Fine, but my question is how are we suppose to pass data from the server-side application to the client script ?

For example if I want to call a js function which take server-side value as input, I still have to call the function like the code below (MVC.Net Razor View) in the page body which is blocked.

<body>
...
<input type="button" value="Test" onclick="DoSomething('@ViewData["SomeValue"]');" />
...
</body>

I found some way to pass data in the script src attribute querystring (http://feather.elektrum.org/book/src.html), but i'm not sure it is the best solution. I'm particulary worried about the caching issue of variables in src querystring. Is there a better way to do that ?

3 Answers

Five years later, but here's what I've decided on as a general strategy:

For server values going to client scripts run at page load time I use disabled input fields in the page:

 <input id='init_data' type='hidden' disabled value='@ViewData["SomeValue"]'>

which avoids any inline javascript, and then grab the value after page load has happened, e.g.

$(document).ready(function(){
  let myValue = $("#init_data").val();
  DoSomething(myValue);
});

For replacing 'onClick' type events which need some server generated values, I replace the onClick attribute with 'data-click' and add an 'event_xxxx' class to attach the trigger event to:

 <input class='event_xxxx' type='button' data-click='@ViewData["SomeValue"]'>

$(document).ready(function(){
    $(".event_xxxx").click(function() {
      let myData = $(this).attr('data-click');
      <do things>
    } ;
});

I use an id for initial data, as that typically relates to a single event happening at page load, whereas my onClicks are generally for multiple items, so I attach the same class to those.

Related