From b017f7cb0136ee33f5d19749a15bf3365a991ac5 Mon Sep 17 00:00:00 2001 From: satotake Date: Sun, 7 Aug 2022 23:15:28 +0900 Subject: [PATCH] livereload: Inject script without head or body tag Currently, Hugo does not inject `livereload` script if html does not contain `` or ``. This sometimes happens if you create new sites without `theme` and it is hard to catch the cause soon. This PR: * Inject livereload script even if html does not include ``, ``, or `` - Modern browsers execute scripts even if they are outside `` - Some js frameworks (confirmed with vite) inject HRM script without `` tag * Append warning script to html if `` or `` is not in html * Fix bug that livereload cannot be appended to the tags with attrs Close #10105 --- .../livereloadinject/livereloadinject.go | 22 ++++++++++++++----- .../livereloadinject/livereloadinject_test.go | 10 ++++++++- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/transform/livereloadinject/livereloadinject.go b/transform/livereloadinject/livereloadinject.go index 32ed55f63ae..d57ba4d244d 100644 --- a/transform/livereloadinject/livereloadinject.go +++ b/transform/livereloadinject/livereloadinject.go @@ -24,16 +24,24 @@ import ( "github.com/gohugoio/hugo/transform" ) +const warnMessage = `"head" or "body" tag is required in html to append livereload script. ` + + "As a fallback, Hugo injects it somewhere but it might not work properly." + +var warnScript = fmt.Sprintf(``, warnMessage) + type tag struct { markup []byte appendScript bool + warnRequired bool } var tags = []tag{ - {markup: []byte(""), appendScript: true}, - {markup: []byte(""), appendScript: true}, + {markup: []byte("")}, {markup: []byte("")}, + {markup: []byte("`, html.EscapeString(src))) i := idx if match.appendScript { - i += len(match.markup) + i += bytes.Index(b[i:], []byte(">")) + 1 + } + + if match.warnRequired { + script = append(script, []byte(warnScript)...) } c = append(c[:i], append(script, c[i:]...)...) diff --git a/transform/livereloadinject/livereloadinject_test.go b/transform/livereloadinject/livereloadinject_test.go index b2ec4483ab1..d5cee79f8c4 100644 --- a/transform/livereloadinject/livereloadinject_test.go +++ b/transform/livereloadinject/livereloadinject_test.go @@ -58,7 +58,15 @@ func TestLiveReloadInject(t *testing.T) { c.Assert(apply("foo"), qt.Equals, "foo"+expectBase+"") }) + c.Run("Html upper", func(c *qt.C) { + c.Assert(apply("foo"), qt.Equals, ""+expectBase+warnScript+"foo") + }) + + c.Run("Html upper with attr", func(c *qt.C) { + c.Assert(apply(`foo`), qt.Equals, ``+expectBase+warnScript+"foo") + }) + c.Run("No match", func(c *qt.C) { - c.Assert(apply("

No match

"), qt.Equals, "

No match

") + c.Assert(apply("

No match

"), qt.Equals, "

No match

"+expectBase+warnScript) }) }