oscarmorrison / md-page

📝 create a webpage with just markdown
https://oscarmorrison.github.io/md-page/
MIT License
1.29k stars 98 forks source link

Call a user-supplied function when conversion complete? #48

Closed Lorp closed 4 years ago

Lorp commented 4 years ago

It would be nice if md-page was able to call a user-supplied function when its own conversion is complete. This user function could always be named onMdPageComplete() — md-page would call this function, if it exists, when it has done its stuff.

My own use case is to implement some images that popup on hover, via a lookup on the contents of the innerText of all the <a> elements.

p1ho commented 4 years ago

It's probably not the ideal thing you wanted, but you're still able to type regular html inside the markdown document. So you could still do something like this

<script src="https://rawcdn.githack.com/oscarmorrison/md-page/master/md-page.js"></script><noscript>

# Regular Markdown Header

<h1 onclick="alert('JS works')">click me</h1>

Note that because the document is basically a giant unclosed <noscript> tag, you won't be able to inject JS using <script> in the middle, but you can either:

  1. include it before you open the <noscript>,
  2. close <noscript> at the end and open a new <script>.

If you try to inject it in the middle, because we're only parsing the first thing that returns from querying noscript, if you open <noscript> again, its content won't be parsed.

Lorp commented 4 years ago

Thanks for this. Yes, I am already closing <noscript> and adding a <script> at the bottom. I added event handlers on the <a> elements with a setTimeout(), which is obviously not ideal. For the time being I’ll add something like this to your code. This should be safe, of course, if the user has not defined such a function.

if (onMdPageComplete)
    onMdPageComplete();
oscarmorrison commented 4 years ago

@Lorp a couple of ways you can do this:

1)

Fork the repo, and then at this line: https://github.com/oscarmorrison/md-page/blob/review/src/script.js#L101

add a window event, window.dispatch ...finished rendering.

2) If you don't want to fork, add a hash to your page. index.html#something, as md-page does a 're-hashing' after the markdown is converted and set on the dom, you can then just listent to onhashchange and it will be fired after the rendering is complete https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onhashchange