[英]How to check if a user is logged_in in a Drupal site via JavaScript?
I know how to check if the user is logged in through PHP, but I need to do some styling when an event occurs, and I created a separate JavaScript file for this.我知道如何检查用户是否通过 PHP 登录,但是我需要在事件发生时进行一些样式设置,为此我创建了一个单独的 JavaScript 文件。 Is this a Drupal variable or something which I can reference too?
这是一个 Drupal 变量还是我也可以引用的东西?
Create a new custom module with hook_init implementation.使用hook_init实现创建一个新的自定义模块。
function [YOUR_MODULE]_init()
{
global $user;
drupal_add_js(array('user_js_uid' => $user->uid), 'setting');
}
Then in your javascript code, check for the value of the variable defined in the module user_js_uid
.然后在您的 javascript 代码中,检查模块
user_js_uid
定义的变量的值。
if(Drupal.settings.user_js_uid == 0)
{
// execute code for non logged in users
}
else
{
// execute code for logged in users
}
If you are waiting for the DOM to be ready and use standard generated Drupal CSS classes, you could do something like (with jQuery):如果您正在等待 DOM 准备就绪并使用标准生成的 Drupal CSS 类,您可以执行以下操作(使用 jQuery):
if( $( "body.not-logged-in" ).length )
{
// user is not logged in
}
For Drupal 8 if you use Drupal.behaviors, you can access the user UID in settings:对于 Drupal 8,如果您使用 Drupal.behaviors,您可以在设置中访问用户 UID:
(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 the userUID === 0
then your user is not connected.因此,如果
userUID === 0
则您的用户未连接。
The "not-logged-in" class doesn't seem to exist in vanilla Drupal 8. But there's "user-logged-in" instead.原版 Drupal 8 中似乎不存在“未登录”类。但取而代之的是“用户登录”类。 Here's one line of CSS I'm using to hide the custom "Register" menu item if a user is logged in:
如果用户登录,这是我用来隐藏自定义“注册”菜单项的一行 CSS:
body.user-logged-in a[href="/user/register"] {display: none; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.