How to check if user logged_in is registered on Drupal site using JavaScript?

I know how to check if a user is registered through PHP, but I need to do some style when an event occurs, and for this I created a separate JavaScript file. Is this a Drupal variable or something that I can reference too?

+6
source share
4 answers

Create a new custom module with hook_init implementation.

function [YOUR_MODULE]_init() { global $user; drupal_add_js(array('user_js_uid' => $user->uid), 'setting'); } 

Then in your javascript code check the value of the variable defined in the user_js_uid module.

 if(Drupal.settings.user_js_uid == 0) { // execute code for non logged in users } else { // execute code for logged in users } 

Hope this helps ... Muhammad

+13
source

If you expect the DOM to be ready and use the standard Drupal CSS classes, you can do something like (with jQuery):

 if( $( "body.not-logged-in" ).length ) { // user is not logged in } 
+11
source

The "unregistered" class does not seem to exist in vanilla Drupal 8. But instead, the "user input". Here is one CSS line that I use to hide the user sign-in element if the user is logged in:

 body.user-logged-in a[href="/user/register"] {display: none; } 
+1
source

For Drupal 8, if you use Drupal.behaviors, you can access the user UID in the settings:

 (function($, Drupal, viewport, settings) { "use strict"; Drupal.behaviors.ifCE = { //the name of our behavior attach: function (context, settings) { var userUID = settings.user.uid; //your code... } })(jQuery, Drupal, ResponsiveBootstrapToolkit, drupalSettings); 

So, if userUID === 0 , then your user is not connected.

+1
source

Source: https://habr.com/ru/post/913373/


All Articles