Discourse API Get Current Topic

AI-generated summary

Discourse API Get Current Topic

The discussion revolves around using the Discourse API to get the current topic. littleviolette is trying to change the URL of a redirect button to a pre-filled link to PM the original poster. To achieve this, they need to get the topic ID and then query the original poster.

littleviolette suggests that the topic ID can be obtained through a JSON query, but is unsure how to do this using JavaScript under Admin > Customization.

renato proposes an alternative approach to get the topic creator’s username using the following code:

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

However, this code does not work directly in the <script/> tag and may require the use of api.onPageChange or another event.

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).