Using api from custom component

AI-generated summary

A user, gar1t, is trying to access the API from a custom component using a script in the HTML body, but the script is not appearing in the page HTML. Arkshine suggests moving the code to the theme component’s Head tab, which allows the script to run and output to the browser console. gar1t confirms this solution, noting that Discourse removes API snippets from the body section, while retaining other script elements.

I’m trying to access the api from a custom component with this snipped in the html body:

<script type="text/discourse-plugin" version="0.8">
  console.log("###########", api.getCurrentUser());
</script>

This snippet however does not appear in the page HTML.

What’s the correct approach here?

Btw, this is the same question posed a few years ago but not answered:

Hello Garrett!

If you put this code in your theme to theme component Head tab,

You should be able to see the output in the browser’s console (there is no HTML being displayed here):

image

Useful guide to learn about Theme component (also Customization > Theme component tag) :+1:

Thank you. I had placed this code in the body section.

It’s surprising to me that the head behavior here is different. It looks like Discourse is removing these api snippets from the body section. Other script elements are retained there.