How to get the request user agent on custom plugin?

AI-generated summary

In a discussion titled ‘How to get the request user agent on custom plugin?’ under the Dev category, Khrisna_Gunanasurya reports that their custom plugin on Discourse v2.9.0.beta1 fails to retrieve the user agent, returning empty values. They note that request.original_url also returns an incorrect domain (http://example.org), suggesting the plugin isn’t receiving the original request. They ask if there’s a global variable to access the original request’s user agent from within plugins. pfaffman responds by cautioning that v2.9.0.beta1 is outdated and difficult to support with new plugins. They question whether the user agent is truly needed server-side, suggesting the front end may be more appropriate. As a workaround, they provide a Rails code snippet to retrieve a user’s previously recorded user agent via UserAuthToken, though it may not reflect the current session: u=User.find(1); uat=UserAuthToken.find_by(user_id: u.id); uat.user_agent. The core issue appears to be that the plugin is not receiving the original HTTP request context, which affects both URL and user agent retrieval.

I build a custom plugin that requires user agent, when it’s deployed, it keeps showing an empty value, how to make the plugin able to get the data from discourse?

I’m using discourse v2.9.0.beta1

update:
Just realized, the plugin on discourse didn’t get the original request.
as this piece of code

<%= request.original_url %>

returns an incorrect url (http://example.org) instead of the correct domain. so this is why the user agent is always empty.

Does someone know what is the global variable that maybe keep the original request user agent and can be called from the custom plugins?

It’s going to be hard to install a new plugin on such an old instance.

Are you sure that Rails needs to know the user agent, and not just the front end (that has easy access to the current browser)? Can you say that you are trying to do?

But here’s a way to get a user agent that has been used by a particular user. It might not be the current user_agent.

u=User.find(1);
uat=UserAuthToken.find_by(user_id: u.id);
uat.user_agent