Skip to content

Instantly share code, notes, and snippets.

@loopthrough
Last active April 14, 2022 11:32
Show Gist options
  • Save loopthrough/17da0f416054401fec355d338727c46e to your computer and use it in GitHub Desktop.
Save loopthrough/17da0f416054401fec355d338727c46e to your computer and use it in GitHub Desktop.
Removing script tags from HTML
package main
import (
"bytes"
"fmt"
"golang.org/x/net/html"
"log"
"strings"
)
var s = `
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" async="" src=""></script>
<script src=""></script>
<script type="text/javascript" async="" src=""></script>
<script type="text/javascript" async="" src=""></script>
<script src="" async=""></script>
<script async="" src=""></script>
<script type="text/javascript" async="" src=""></script>
<script async="" src=""></script>
<link rel="stylesheet" media="screen" href=""/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<style type="text/css">.at-icon{fill:#fff;border:0}.at-icon-wrapper{display:inline-block;overflow:hidden}</style></head><body></body></html>`
func main() {
doc, err := html.Parse(strings.NewReader(s))
if err != nil {
log.Fatal(err)
}
var content bytes.Buffer
removeScript(doc)
html.Render(&content, doc)
fmt.Printf("%s\n", content.Bytes())
}
func removeScript(n *html.Node) {
// if note is script tag
if n.Type == html.ElementNode && n.Data == "script" {
n.Parent.RemoveChild(n)
return
}
// traverse DOM
for c := n.FirstChild; c != nil; c = c.NextSibling {
defer removeScript(c)
}
}
@loopthrough
Copy link
Author

Using defer to eliminate need to remember the references to siblings.
They were originally used because in recursion current node would be removed and would lose siblings so recursion would stop.

@LeMoussel
Copy link

With recursion , there are some disadvantages to iterate over parsed tree, namely:

  • Bigger memory consumption
  • Pointy CPU usage

To solve these issues you can process data while reading from the stream.
See Parsing HTML with Go using stream processing (https://mionskowski.pl/html-golang-stream-processing)

@loopthrough
Copy link
Author

Thanks for the comment and for the link to the informative article. I guess that in languages which don't optimise recursions it is smart to avoid it for performance reasons where matters more than expressivity of the concept. Streaming the tokens from the tokeniser is a nice idea.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment