I’m generating a service worker to cache my website’s assets. Then I added it to my HTML file like this:
{{- (resources.GetMatch '/js/sw.js' | resources.ExecuteAsTemplate '/js/sw.js' . | minify).RelPermalink -}}.
However, in the rendered HTML, I get it like '\/js\/sw.min.js' instead of the expected '/js/sw.min.js'. What am I doing wrong? I tried adding htmlUnescape and safeHTML, but that didn’t help.
It’s not creating a big issue as the service worker is still working fine, however, I was just willing to know the reason behind this.
Are you sure this works for you? I get an error if I try to use single quotes. Use double quotes instead.
Oh yeah, I was using backticks (`) in my original file, but when I pasted it to the forums, I switched to the single quotes because of formatting and I didn’t try it. But I updated it to use double quotes in my file right after posting it here.
In that case I cannot replicate your issue. Please provide a sample repo.
navigator.serviceWorker.register({{- (resources.GetMatch "/js/sw.js" | resources.ExecuteAsTemplate "/js/sw.js" . | minify).RelPermalink -}});
Note the lack of quotes outside the {{}}.
Oh, that was it. Since without Hugo processing I was adding the service worker like navigator.serviceWorker.register('/js/sw.js'), I thought, I’ll just have to replace the content within the quotes with the Hugo code.
Thanks for the help!