This documentation covers a prerelease version of the software. Follow this link to view the documentation for the stable version (3.0) instead.

Postprocessor Extension Example

Purpose

Inject a Copy button inside every <pre> element of the converted HTML output so readers can copy code snippets to the clipboard with a single click.

sample-api-doc.adoc

= API Reference

== Authentication

Send your API key in the request header:

[source,shell]

curl -H "Authorization: Bearer <token>" api.example.com/v1/users


CopyButtonPostprocessor

copy-button-postprocessor.js
export default function (registry) {
  registry.postprocessor(function () {
    this.process(function (doc, output) {
      return output
        .replace(/(<pre[^>]*>)/g, '<div class="code-wrapper"><button class="copy-btn" onclick="navigator.clipboard.writeText(this.nextElementSibling.textContent)">Copy</button>$1')
        .replace(/<\/pre>/g, '</pre></div>')
    })
  })
}

Usage

import { Extensions, convertFile } from '@asciidoctor/core'
import registerCopyButtonPostprocessor from './copy-button-postprocessor.js'

const registry = Extensions.create()
registerCopyButtonPostprocessor(registry)

const html = await convertFile('sample-api-doc.adoc', { to_file: false, extension_registry: registry })
// Every <pre> element is now wrapped with a copy button:
// <div class="code-wrapper">
// <button class="copy-btn" onclick="...">Copy</button>
// <pre class="highlight"><code ...>curl ...</code></pre>
// </div>