How do you force a script to refire on every page load in Discourse?

I have been working on something that needs to be fired when entering a topic. I don’t know if this is overly complicated or the proper way to do it, but this is what I’ve found works well so far:

<script type="text/discourse-plugin" version="0.8.13">
    api.addPostTransformCallback((t) => {
        // post is topic post && element doesn't already exist
        if (t.post_number === 1 && $("#test-id").length == 0) {
            $(function() {
                var testText = '<h1 id="test-id">Test</h1>';
                $("#post_1 .regular.contents").before(testText);
            });
        }
    });
</script>

Try this out in a theme component. It will add the word “Test” to the first post in every topic.

1 Like