Jump to content

Using Javascript to detect logged in status and modify components?

Recommended Posts

Posted

Hi guys,

I'm trying to figure out not only if it's possible to check if a user is logged in or not,  but then hide my CTA button if a user is detected as logged in.

Does anyone have any idea if this is possible/how to do it? Ideally the base state would be the CTA being visible to unauthenticated users, then once a user is logged in, the css of the CTA button would be modified to display:none; and vice versa.

The CTA is a 'Get Started' button that links to my own account signup page for a Member's Area account and I'd like it to only display for new/logged out users if possible.

  • Replies 10
  • Views 5k
  • Created
  • Last Reply

Top Posters In This Topic

Posted (edited)
On 12/3/2023 at 11:21 AM, JabberDesigns said:

I'm trying to figure out not only if it's possible to check if a user is logged in or not

You can either use JS to call the User Account API to check if the user is authenticated (more secure), or look for the unauth class on the Login link which will indicate the user is not logged in (less secure). 

For example, adding this JS to code injection would add an "authenticated" class to the page body, allowing you to use this class as a CSS selector.

<script>
  document.addEventListener('DOMContentLoaded', () => {
    if (UserAccountApi.isUserAuthenticated()) document.body.classList.add("authenticated")
  });
</script>

 

Edited by paul2009

Me: I'm Paul, a SQSP user for >18 yrs & Circle Leader since 2017. I value honesty, transparency, diversity and good design ♥.
Work: Founder of SF.DIGITAL. We provide high quality original extensions to supercharge your Squarespace website. 
Content: Views and opinions are my own. Links in my posts may refer to my own SF.DIGITAL products or may be affiliate links.
Forum advice is completely free. You can thank me by selecting a feedback emoji. Buying a coffee is generous but optional.

Posted (edited)

Hey @paul2009,

Thanks for your response!

Could you possibly give me a quick coding example of this? I'm inexperienced with Squarespace's API, and all I can seem to find about it is telling me to register for the Squarespace Developer OAuth in order to make API calls. (I'm sure there must be a simpler way?)

I currently have this code that I feel should do the trick, I'm just not sure on the formatting/API details to make it work properly atm.

 

<!-- Show/Hide CTA button -->
<script>
(function () { 
    const url = 'https://api.squarespace.com/v1/profiles';
    const headers = {
      'Authorization': 'Bearer MY-API-KEY',
      'Content-Type': 'application/json'
    };

    // Get user authentication status from Squarespace API
    fetch(url, { headers })
    fetch(url, { credentials: 'include' })
        .then(response => {
            if (response.status === 200) {
                // If the user is authenticated, hide the CTA button
                document.getElementById("yui_3_17_2_1_1702054210072_484").style.display = "none";
            } else {
                // If the user is unauthenticated, show the CTA button
                document.getElementById("yui_3_17_2_1_1702054210072_484").style.display = "block";
            }
        })
        .catch(error => {
            console.error("Error:", error);
        });
})();
</script>

 

Edited by JabberDesigns
updating code snippet
Posted
On 12/8/2023 at 5:36 PM, JabberDesigns said:

Could you possibly give me a quick coding example of this?

Sure. UserAccountApi.isUserAuthenticated() will return true when logged in.

Did this help? Please give feedback by clicking an icon below  ⬇️

Me: I'm Paul, a SQSP user for >18 yrs & Circle Leader since 2017. I value honesty, transparency, diversity and good design ♥.
Work: Founder of SF.DIGITAL. We provide high quality original extensions to supercharge your Squarespace website. 
Content: Views and opinions are my own. Links in my posts may refer to my own SF.DIGITAL products or may be affiliate links.
Forum advice is completely free. You can thank me by selecting a feedback emoji. Buying a coffee is generous but optional.

Posted
On 12/11/2023 at 10:09 PM, paul2009 said:

Sure. UserAccountApi.isUserAuthenticated() will return true when logged in.

Did this help? Please give feedback by clicking an icon below  ⬇️

Do you have any documentation about User Account API? 

  • 4 months later...
Posted

@paul2009

 

I'd like to try using your idea of looking for "unauth" but it appears that every page (regardless of being logged in/ authenticated) contains both these classes:   

<span class="unauth">Login</span>
  <span class="auth">Account</span>

 

Is there another way to search each page to see if users are logged in or not (avoiding the API... I am not very tech savvy) 

Posted (edited)
14 hours ago, dhawkins said:

I'd like to try using your idea of looking for "unauth" but it appears that every page (regardless of being logged in/ authenticated) contains both these classes:   

<span class="unauth">Login</span>
<span class="auth">Account</span>

Are you testing this with a Customer Account? I ask because in this context "logged in" refers to being logged into a Customer Account, not logged into Squarespace as a contributor.

If a visitor is not logged into their Customer Account, the webpage should contain the first span (including the .unauth class). When they are logged into their customer account, the page should contain second span (with the .auth class) instead. 

If you are seeing something different, please post a link to the page on your site and share details of a customer account we can use to test it. 

Edited by paul2009

Me: I'm Paul, a SQSP user for >18 yrs & Circle Leader since 2017. I value honesty, transparency, diversity and good design ♥.
Work: Founder of SF.DIGITAL. We provide high quality original extensions to supercharge your Squarespace website. 
Content: Views and opinions are my own. Links in my posts may refer to my own SF.DIGITAL products or may be affiliate links.
Forum advice is completely free. You can thank me by selecting a feedback emoji. Buying a coffee is generous but optional.

  • 2 months later...
Posted

Hello all,

I am in the process of creating a B2B e-Commerce site. I have hidden the price in all pages and the "Add to cart" button. Now I am trying to validate whether a customer is authenticated or logged in and then wanted to enable the price and the add to cart button.

Searched the forums and tried multiple methods shown below, unfortunately, nothing worked. Please excuse for any mistakes as I am new to SS. I tried the following in the Page header code injection and currently on the trial version of 7.1 Template. Plain CSS works in the page header code, but I want to validate whether user is authenticated/logged in before adding the CSS.

1. UserAccountApi.isUserAuthenticated() 

2. document.getElementById

3. document.getElementsByClassName("classname");

Any code example or help will be appreciated. 

Additional info on what I have done so far:

Prices and the "Add to Cart" button is disabled using Custom CSS code as below. Please feel free to suggest other options.

.ProductItem-product-price {
    display: none !important;
}
.product-price{
    display: none !important;
}
.sqs-add-to-cart-button-wrapper {
    display: none !important;
}

Thanks.

Posted

You can add this to your Code Injection (best to put it in the site-wide one rather than on each individual page):

<script>
  document.addEventListener('DOMContentLoaded', () => {
    if (UserAccountApi.isUserAuthenticated()) document.body.classList.add('logged-in')
  });
</script>

Then in your custom CSS:

body:not(.logged-in) {
  .ProductItem-product-price {
      display: none !important;
  }
  .product-price{
      display: none !important;
  }
  .sqs-add-to-cart-button-wrapper {
      display: none !important;
  }
}

Hopefully it works and I haven't made mistakes writing the code.

Andrew

Square Ace

Enhancing Squarespace websites for over a decade. I am an expert in writing custom code for the Squarespace platform.
Tailor-made, reusable solutions to your problems, whether it's styling, layout or functionality.
Maverick Squarespace Designers, I'll be your Goose. If your tools are holding back your creative vision, maybe I can help.
I also build useful plugins for Squarespace (with some really positive reviews) including the popular high-quality video background plugin.

Create an account or sign in to comment

You need to be a member in order to leave a comment

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.