Skip to content

Commit

Permalink
Add script's integrity and crossorigin attributes (#173)
Browse files Browse the repository at this point in the history
When using `<script>` to pull a library from a CDN, it's usually a good
idea to attach an integrity check so that if they get hacked and someone
changes all the script, malicious scripts don't get executed on your
website.

To achieve this, you need to attach `integrity` and `crossorigin` to
your `<script/>` tag

```go
Script(
	Scr("https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js"),
	Integrity("sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW"),
	CrossOrigin("anonymous"),
)
```
Turns into
```html
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" 
    integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" 
    crossorigin="anonymous"></script>
```

Hint for whoever likes unpkg.com, adding `?meta` at the end of any
script you import form them will give you the current `integrity` for
the file. Example: https://unpkg.com/three@0.165.0/build/three.cjs?meta
  • Loading branch information
markuswustenberg committed Jun 6, 2024
2 parents 5fa128b + 600b6c3 commit d944acd
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
8 changes: 8 additions & 0 deletions html/attributes.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ func Controls() g.Node {
return g.Attr("controls")
}

func CrossOrigin(v string) g.Node {
return g.Attr("crossorigin", v)
}

func Defer() g.Node {
return g.Attr("defer")
}
Expand Down Expand Up @@ -130,6 +134,10 @@ func ID(v string) g.Node {
return g.Attr("id", v)
}

func Integrity(v string) g.Node {
return g.Attr("integrity", v)
}

func Lang(v string) g.Node {
return g.Attr("lang", v)
}
Expand Down
2 changes: 2 additions & 0 deletions html/attributes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,14 @@ func TestSimpleAttributes(t *testing.T) {
"cols": Cols,
"colspan": ColSpan,
"content": Content,
"crossorigin": CrossOrigin,
"enctype": EncType,
"for": For,
"form": FormAttr,
"height": Height,
"href": Href,
"id": ID,
"integrity": Integrity,
"lang": Lang,
"loading": Loading,
"max": Max,
Expand Down

0 comments on commit d944acd

Please sign in to comment.