web.dev
web.dev copied to clipboard
Fix inline scripts in patterns
An inline <script>
in web.dev patterns requires using {% set script %}
to avoid CSP issues such as ones in https://web.dev/new-patterns-july-2022/

Here's a quick way to fix it for instance:
diff --git a/src/site/content/en/patterns/layout/gentle-flex/demo.njk b/src/site/content/en/patterns/layout/gentle-flex/demo.njk
index a8978a8fd..003bf4445 100644
--- a/src/site/content/en/patterns/layout/gentle-flex/demo.njk
+++ b/src/site/content/en/patterns/layout/gentle-flex/demo.njk
@@ -93,7 +93,7 @@ patternId: layout/gentle-flex
<div>Resize ⤴</div>
</footer>
- <script>
+ {% set script %}
const examples = ['Sibling', 'Sibling with a long name', 'Maybe a whole paragraph of content, you never know!', 'Short']
let position = 0
@@ -103,6 +103,7 @@ patternId: layout/gentle-flex
document.querySelector('article').appendChild(newNode)
}
- </script>
+ {% endset %}
+ <script>{{ script | minifyJs | cspHash | safe }}</script>
</body>
</html>
A more complicated problem is the inability to create CSP hashes (using cspHash
) for import * from ...
inside {% set script %}
. It happens at least for https://cdn.skypack.dev/blingblingjs
and https://cdn.skypack.dev/roving-ux
at least from what I can see.

oh snap, so i need to go update each example with these additions?
Yes, the use of inline scripts is documented in the Full HTML demo page: https://web.dev/patterns/example-set/full-html-demo/demo.html
@devnook See https://github.com/GoogleChrome/web.dev/pull/8480#issuecomment-1208953649
i'll go through the remaining demo's that were type=module and had imports, and bundle them so they dont have imports. sounds like inlining it all without imports will resolve the current csp limitations
seems like it'd be nice to allow these for the future tho?
patch PR here https://github.com/GoogleChrome/web.dev/pull/8499
Fixed in #8499