Skip to content

Commit d01da05

Browse files
committed
Fix HTML detection, ref #164
1 parent 1a0f481 commit d01da05

2 files changed

Lines changed: 13 additions & 3 deletions

File tree

engine/rendering.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"github.com/xyproto/algernon/themes"
2222
"github.com/xyproto/algernon/utils"
2323
lua "github.com/xyproto/gopher-lua"
24+
"github.com/xyproto/huldra"
2425
"github.com/xyproto/splash"
2526
"github.com/yosssi/gcss"
2627

@@ -654,7 +655,7 @@ func (ac *Config) PongoPage(w http.ResponseWriter, req *http.Request, filename s
654655
}
655656

656657
// Check if we are dealing with HTML
657-
if strings.Contains(buf.String(), "<html>") {
658+
if huldra.IsHTML(buf.Bytes()) {
658659

659660
if linkInCSS || linkInGCSS {
660661
// Link in stylesheet

engine/sse.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"text/template"
88

99
"github.com/xyproto/algernon/utils"
10+
"github.com/xyproto/huldra"
1011
)
1112

1213
const autoloadTemplate = `
@@ -96,16 +97,24 @@ func InsertScriptTag(htmldata, js []byte) []byte {
9697
return js
9798
}
9899

100+
// TODO: Write a better HTML manipulator. Create an external package.
101+
99102
// Place the script at the end of the body, if there is a body
100103
switch {
101104
case bytes.Contains(htmldata, []byte("</body>")):
102105
return bytes.Replace(htmldata, []byte("</body>"), append(js, []byte("</body>")...), 1)
103106
case bytes.Contains(htmldata, []byte("<head>")):
104107
// If not, place the script in the <head>, if there is a head
105108
return bytes.Replace(htmldata, []byte("<head>"), append([]byte("<head>"), js...), 1)
106-
case bytes.Contains(htmldata, []byte("<html>")):
109+
case huldra.IsHTML(htmldata):
110+
const maxPosition = 200
111+
htmlTagBytes, err := huldra.GetHTMLTag(htmldata, maxPosition) // try to retrieve the entire <html[...]> tag
112+
if err != nil {
113+
htmlTagBytes = []byte("<html>")
114+
}
115+
htmlAndHeadTagBytes := append(htmlTagBytes, []byte("<head>")...)
107116
// If not, place the script in the <html> as a new <head>
108-
return bytes.Replace(htmldata, []byte("<html>"), append(append([]byte("<html><head>"), js...), []byte("</head>")...), 1)
117+
return bytes.Replace(htmldata, htmlTagBytes, append(append(htmlAndHeadTagBytes, js...), []byte("</head>")...), 1)
109118
}
110119

111120
// In the unlikely event that no place to insert the JavaScript was found, just add the script tag to the end

0 commit comments

Comments
 (0)