Is there a way to check user permissions in javascript? I have a segment of code that I only want visible if the user has the proper permissions, and I think it would be easiest way to check the permissions, and then just set the segment to display: none; if the user doesn't have the right permissions.

  • If all you need is to hide block from users with certain roles, you can directly set permission to that block. Go to that specific block management page in /admin/structure/block, find "Roles" in "Visibility settings" and select which roles should see that block. Block will not be rendered at all for other users. (This is ok for single user permission, select role that has it, but if you need to hide it by multiple permissions shared by different roles you cant set this that way of couse) – tdd Jul 24 '15 at 6:41

It is not secure to only rely on Javacript. It is better to separate that .js function which needs permission to execute from other codes then put in a file and load that .js file from your hook_preprocess_page if the user has permission (or some role). I implement this idea with user roles, you may use another strategy for checking the permission.

function THEME_preprocess_page(&$var){
      global $user;
            drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/Your_js.js');


in your theme directory, I supposed you placed your .js files in /js directory. So you should create Your_js.js file in that directory and put that function inside it. If the user has appropriate role, that file with that function in it will be loaded and you can use it later, otherwise it won't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.