Discourse API Get Current Topic

HI!

I see that Discourse’s API script plug-in can get the current user:

<script type="text/discourse-plugin" version="0.8.18">
    if(api.getCurrentUser() != null) {
        $("#logged-in-user").text(" " + api.getCurrentUser().username);
    }
</script>

Is there a similar command to get the current topic? My use case is to change the URL of the redirect button at the end of a post to a pre-filled link to PM the original poster. In order the find the username of the original poster, it seems like I would need to get the topic id first, then query the original poster via "/t/<TOPIC_ID>.json"?

The button plug-in has <TOPIC_ID> built in, but I am not sure how that can be done using javascript under Admin > Customization. Thank you!

I’m not sure if this is the best approach, but it’s possible to get the topic creator username like this:

const controller = Discourse.__container__.lookup("controller:topic")
const username = constroller.get("model.details.created_by.username")

This doesn’t work directly in the <script/> tag, you’d probably want to use it on a api.onPageChange or some other event (in a quick test it also worked on a setTimeout with 0ms, but I don’t know if there are side effects).

1 Like