Audience: Advanced (comfortable with JavaScript/jQuery)
What this shows
How to customize Markdown-generated HTML after the fact, since Snowman’s
internal Markdown renderer (the marked library) isn’t exposed globally for
you to reconfigure directly from a UserScript passage.
How it works
- Snowman converts Markdown to HTML internally when it renders a passage.
That HTML is inserted into
tw-passagebefore thesm.passage.shownevent fires, so listening for that event is the right time to adjust it. - The first rule finds any link inside
tw-passagewhosehrefstarts withhttp(i.e., an external link written with Markdown’s[text](url)syntax) and addstarget="_blank" rel="noopener noreferrer"to it, just like the “External Links” example does by hand. - The second rule looks for fenced code blocks (
code, which Markdown turns into<pre><code>) and inserts a small “Code:” label above each one that doesn’t already have one.
Using this in your own story
- Register a
sm.passage.shownlistener inUserScript. - Use jQuery selectors scoped to
tw-passageto find and adjust whatever Markdown-generated elements you want to enhance (links, code blocks, tables, images, etc.) — anything you could do with jQuery to any other HTML on the page.
Full source
:: StoryData
{
"ifid":"A1B71AA6-BD68-4DE8-A56F-7F287516BDF9"
}
:: StoryTitle
Enhancing Markdown Output in Snowman
:: UserScript[script]
/*
Post-process the already-rendered Markdown output after each passage is
shown, instead of trying to reconfigure the internal Markdown renderer.
*/
$(document).on('sm.passage.shown', function () {
// Make Markdown-generated links to other sites open safely in a new tab.
$('tw-passage a[href^="http"]').attr('target', '_blank').attr('rel', 'noopener noreferrer');
// Label fenced code blocks generated by Markdown.
$('tw-passage pre code').each(function () {
var $pre = $(this).parent();
if ($pre.prev('.code-label').length === 0) {
$('<div class="code-label">Code:</div>').insertBefore($pre);
}
});
});
:: Start
Check out [the Snowman repository](https://github.com/videlais/snowman) to learn more.
```
console.log("hello");
```
← Previous: Custom Events for Notifications · All examples · Next: Accessible Passage Announcements →