TimKern
TimKern
NNuxt
Created by TimKern on 7/6/2023 in #❓・help
render:html hook in defineNitroPlugin duplicates the whole page content
i am writing a plugin for a "table of content" component so i can get all headings for it. i am using the render:html hook to manipulate the html. After manipulating the html the page will show me the whole server side rendered page and beneath it shows me the whole server side rendered page 😓 here is the plugin code. am i using the hook wrong 🤔
import { parse } from 'node-html-parser'

export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('render:html', (html, { event }) => {
html.body = html.body.map((chunk) => {
const d = parse(chunk)
const tocContainer = d.querySelectorAll('.toc-list')
if (!tocContainer.length) {
return
}
const headings = d.querySelectorAll(
':is(h1,h2,h3,h4,h5,h6)'
)
headings.forEach((heading) => {
const text = heading.textContent || heading.innerText
if (!heading.id && !heading.attributes.id) {
const id = text
.toLowerCase()
.replace(/[^a-z0-9 ]/g, '')
.replace(/\s/g, '-')
.replace(/^-*|-*$/g, '')
heading.setAttribute('id', id)
tocContainer.forEach((toc) => {
toc.appendChild(
parse(
`<li class="toc-${heading.rawTagName}"><a href="#${id}">${text}</a></li>`
)
)
})
} else {
tocContainer.forEach((toc) => {
toc.appendChild(
parse(
`<li class="${heading.rawTagName}"><a href="#${
heading.id || heading.attributes.id
}">${text}</a></li>`
)
)
})
}
})
return d.toString()
})
})
})
import { parse } from 'node-html-parser'

export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('render:html', (html, { event }) => {
html.body = html.body.map((chunk) => {
const d = parse(chunk)
const tocContainer = d.querySelectorAll('.toc-list')
if (!tocContainer.length) {
return
}
const headings = d.querySelectorAll(
':is(h1,h2,h3,h4,h5,h6)'
)
headings.forEach((heading) => {
const text = heading.textContent || heading.innerText
if (!heading.id && !heading.attributes.id) {
const id = text
.toLowerCase()
.replace(/[^a-z0-9 ]/g, '')
.replace(/\s/g, '-')
.replace(/^-*|-*$/g, '')
heading.setAttribute('id', id)
tocContainer.forEach((toc) => {
toc.appendChild(
parse(
`<li class="toc-${heading.rawTagName}"><a href="#${id}">${text}</a></li>`
)
)
})
} else {
tocContainer.forEach((toc) => {
toc.appendChild(
parse(
`<li class="${heading.rawTagName}"><a href="#${
heading.id || heading.attributes.id
}">${text}</a></li>`
)
)
})
}
})
return d.toString()
})
})
})
1 replies