Karta.Tracking.HTML (Karta v1.0.0)

Finds and rewrites the links of an HTML body, and adds the open pixel, without parsing and re-serialising the document: every byte outside a rewritten href value and the inserted pixel stays as it was, so conditional comments, unusual markup and white space survive.

The scanner follows the HTML tokenizer (WHATWG HTML, "Tokenization") far enough to find tags reliably:

  • comments (<!-- ... -->, also ended by --!>, and the empty <!--> and <!--->), <!...> and <?...> are skipped, so a link inside a comment (an Outlook conditional comment, too) is left alone;
  • the content of script, style, title, textarea, xmp, iframe, noembed and noframes is skipped up to its end tag; after plaintext nothing is markup;
  • attribute values may be double-quoted, single-quoted or unquoted; attribute names are compared without case, and of a repeated attribute the first counts, as in browsers;
  • a tag cut off by the end of the input is no tag.

A link is the href of an a or area start tag. Its value is decoded as a browser decodes it, but only as far as that is certain: &amp;, &lt;, &gt;, &quot;, &apos; and numeric references ending in ; are decoded, and an & that cannot start a reference stays; a value with any other reference is left alone. Leading and trailing white space is removed. A link is trackable when the result is an absolute http or https URL with a host, of printable ASCII only (no white space), at most 2048 bytes, that URI.new/1 accepts. Every other link - mailto:, tel:, relative links, fragments, javascript: - is never changed.

Postal's +notrack marker is kept (MIT, Postal's MessageParser): when links are rewritten, a link written https+notrack://... is not tracked and is written as https://....

Summary

Types

Returns the tracking URL for a trackable URL, or nil to keep the link.

Functions

The trackable URLs of the links, in document order (repeated URLs repeated).

The document with its links and the pixel. Options

Types

Functions

links(html)

@spec links(binary()) :: [String.t()]

The trackable URLs of the links, in document order (repeated URLs repeated).

rewrite(html, opts)

@spec rewrite(binary(), keyword()) :: binary()

The document with its links and the pixel. Options:

  • :link - a link_fun/0; nil (default) changes no link. With a function, +notrack links lose their marker.
  • :pixel - the URL of the open pixel, or nil (default). The pixel goes before the last </body> end tag, or at the end of the document (before its final line breaks) when there is none.