Skip to content

Commit

Permalink
Use a nonce on inline JavaScript
Browse files Browse the repository at this point in the history
This change has been made so that Smart Answers is compatible with
upcoming changes to the GOV.UK Content Security Policy [1].

This adds a nonce so this JavaScript will be allowed to execute. If the
CSP does not have a nonce generator then setting nonce: true will have
no effect. As this switches to using the Rails `javascript_tag` helper
it also wraps the output JS in old-school CDATA tags, which looks a bit
legacy but is benign.

This changes the use of defer="false" to be just a defer attribute. The
usage of defer on inline script is unusual as it only applies when src
is set [2].

I'm not sure why the `defer="false"` attribute was originally added (the
commit [3] doesn't explain it) however it is now needed as part of
Slimmer reorganising JavaScripts. Slimmer moves this JS to the head (and
strips the `="false"`) so the change to `defer: true` is just to make
the code for JS reflect what it actually used. Since it now seems to be
used as a hack for Slimmer, I've labelled it as so.

[1]: alphagov/govuk_app_config#279
[2]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer
[3]: a5c4e14
  • Loading branch information
kevindew committed Jan 18, 2023
1 parent 46894fd commit fd0d336
Showing 1 changed file with 3 additions and 2 deletions.
5 changes: 3 additions & 2 deletions app/views/smart_answers/visualise.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@
<%= stylesheet_link_tag 'visualise' %>
<% end %>

<script defer="false">
<%# Use of defer is to hoist this JS to head with slimmer, it's totally a hack %>
<%= javascript_tag(nonce: true, defer: true) do -%>
var adjacencyList = <%= JSON.pretty_generate(@graph_data).html_safe %>;
</script>
<%- end %>

<%= render "govuk_publishing_components/components/title", {
context: "Flow visualisation for",
Expand Down

0 comments on commit fd0d336

Please sign in to comment.