Back

Category: Custom Scripts & CSS

How to add JavaScript code based on user login and membership level

Use cases:

Use case one: Redirect user to a page if user is logged in or not logged in.

Imagine you want to redirect a user to a page based on their login status. Now we can do it easily with some JavaScript code. Here is the code example you can copy, paste, and use:

If you want to send user to a custom page called :  /en/audio-library
// IF USER IS LOGGED IN
let currentUrl = window.location.href;
console.log('current url', currentUrl) // edge case.. don't redirect from any page. one page can have multiple version with lang or without lang. you can create any logic here.. 
if (!window.user && ( currentUrl == 'https://trial.ezycourse.com/en/home' || currentUrl == 'https://trial.ezycourse.com' || currentUrl == 'https://trial.ezycourse.com/en') ) { 
    console.log('matched')
    window.location.href = '/en/audio-library';
  
}

If you want to send user to a custom page if user is not logged in : /custom-page
// IF USER IS NOT LOGGED IN
if (!window.user && // add more condition as per your need) { 
  window.location.href = '/custom-page';
}

Use case two: Redirect user to a page if user has a membership plan. Imagine the name of the plan is “My plan“

// REDIRECT USER BASED ON MEMBERSHIP AND MEMBERSHIP PLAN TYPE
if (window.myMemberships.length) { 
  for(let membership of myMemberships){
     if(membership.plan_name == 'My plan'){
         window.location.href = '/custom-membership-page-for-my-plan';
     }
  }
}

Data is available inside window object as

window.user
window.myMemberships // it's an array of membership objects