hugo icon indicating copy to clipboard operation
hugo copied to clipboard

Builtin Template Strict Content-Security-Policy Supports

Open septs opened this issue 1 year ago • 1 comments

Motivation

Make Content-Security-Policy by default supports.

Proposal

  1. Improve builtin template, move inline script to standalone file

Sample

sample origin e.g:

https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/disqus.html

  1. extract javascript inline script as file, use document.currentScript feature get current script dataset, e.g: document.currentScript.dataset.identifer, document.currentScript.dataset.title, etc

  2. avoid user copy implementation modify it.

_internal/disqus.html

{{- if not .Site.Config.Privacy.Disqus.Disable }}
{{- $resource := resources.Get "_internal/disqus.js" | fingerprint }}
<div id="disqus_thread"></div>
<script
  src="{{ $resource.Permalink }}"
  integrity="{{ $resource.Data.Integrity }}"
  async
  defer
  data-identifer="{{ .Params.disqus_identifier }}"
  data-title="{{ .Params.disqus_title }}"
  data-url="{{ .Params.disqus_url }}"
  data-shortname="{{ .Site.DisqusShortname }}"
>
</script>
<noscript> ... no script warning ... </noscript>
{{- end }}

_internal/disqus.js

(function () {
  if (["localhost", "127.0.0.1"].includes(location.hostname)) {
    document.getElementById('disqus_thread').innerHTML = 'Disqus comments not available by default when the website is previewed locally.';
    return;
  }
  var dataset = document.currentScript.dataset;
  window.disqus_config = function () {
    if (dataset.identifer) this.page.identifier = dataset.identifer;
    if (dataset.title) this.page.title = dataset.title;
    if (dataset.url) this.page.url = dataset.url;
  };
  var element = document.createElement('script');
  element.async = true;
  element.src = '//' + dataset.shortname + '.disqus.com/embed.js';
  element.dataset.timestamp = Date.now();
  document.head.appendChild(element);
})();

septs avatar Sep 14 '22 11:09 septs

The proposed change won't work because this.page in the original script is part of window.disqus_config which is missing in the changed version. I think it can be fixed, but the most clear thing would be to rewrite it to not use this at all.

earthboundkid avatar Sep 16 '22 13:09 earthboundkid

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

github-actions[bot] avatar Jan 10 '23 02:01 github-actions[bot]