Access variable in front-end from masterPage.js

Hi all,

What i am trying to do is open a lightbox on my Cart page only if a product is not yet in the user’s cart.
For that I use : oncartchanged() (https://www.wix.com/corvid/reference/wix-stores/oncartchanged) in masterPage.js

import wixStores from 'wix-stores';

const MEMBER_ID = "2ff98628-88fa-6f0d-7809-0aaa8708c8f7";

var isMemberInCart = false;

$w.onReady(function () {
    wixStores.onCartChanged((cart) => {
        const cartLineItems = cart.lineItems;
        if(cartLineItems.length === 0 ) {
            isMemberInCart = false;
        } else {
            isMemberInCart = false;
            cartLineItems.forEach((item) => {
                if(item.productId === MEMBER_ID) {
                    isMemberInCart = true;
                }
             });
         }
    });
});

export function getCart() {
    console.log('isMemberInCart: ' + isMemberInCart);
    return isMemberInCart;
}

The code in onCartChanged seems to work (I tested with logs), but the getCart() function always returns false.

Here is the code in the Cart page

import wixWindow from 'wix-window';
import { getCart } from 'public/pages/masterPage.js';

$w.onReady(function () {
    if(!getCart()) {
        wixWindow.openLightbox("Add Member");
    }
});

I haven’t found an easier way to access the shopping cart.

Thanks for your help!

Hey I was trying to do something similar where certain elements of my cart page are either shown or hidden based on if there is any items in the cart or not. Hope my code helps you.
Code on the cart page

import wixStores from 'wix-stores';
import { getCurrentCart } from 'backend/events.jsw';

//checks cart on page load
$w.onReady(async function () {
 const results = await getCurrentCart();
 let quantity = results.totals.quantity;
    console.log("this message appears from the getCurrentCart function" + quantity);
 if (quantity > 0) {
        $w("#text35").expand();
        $w("#box1").expand();
    } 

});
//checks cart when the user deletes items from the cart page itself
let quantity = 10;// random value

$w.onReady(function () {
    wixStores.onCartChanged((cart) => {
        quantity = cart.totals.quantity;
        console.log("this message appears from the onCartChanged function" + quantity);
 if (quantity > 0) {
            $w("#text35").expand();
            $w("#box1").expand();
        } 

    });

});

Code on backend/events.jsw

import wixStoresBackend from 'wix-stores-backend'
export function getCurrentCart() {
 return wixStoresBackend.getCurrentCart();
}