Untitled

 avatar
unknown
plain_text
2 months ago
19 kB
7
Indexable
function storeUTMParameters() {
    let validUTMParams = {};
    // UTM Slug conditions
    const slugConditions = [
        { slugs: ["/blog", "/product-updates", "/newsroom"], campaign: 'blog' },
        { slugs: ["/downloads", "/case-studies"], campaign: 'content' },
        { 
            slugs: [
                "/swift-code-checker",
                "/ssic-code-checker",
                "/spend-calculator",
                "/spend-management-calculator",
                "/idr-payroll-calculator",
                "/launchpad",
                "/investor-list-south-east-asia",
                "/currency-converter"
            ], 
            campaign: 'tools' 
        },
        { 
            slugs: [
                "/zh-SG", 
                "/id", 
                "/id-ID", 
                "/hk", 
                "/zh-HK", 
                "/zh-Hans-HK",
                "/business-account", 
                "/expense-management", 
                "/corporate-card", 
                "/global-payments", 
                "/aspire-ai", 
                "/integrations", 
                "/bill-pay", 
                "/api", 
                "/cashback", 
                "/pricing",
                "/vendor-management",
                "/global-collections",
                "/approval-flows",
                "/manajemen-biaya",
                "/budgets",
                "/multi-currency-account",
                "/payable-management",
                "/pembayaran-internasional",
                "/cash-management",
                "/receivable-management",
                "/insights",
                "/global-account",
                "/payment-gateway",
                "/employee-claims",
                "/invoice-management",
                "/instant-payouts",
                "/payment-links",
                "/rekening-bisnis",
                "/kartu-pembayaran-korporat",
                "/bulk-payments",
                "/xero",
                "/harga",
                "/multi-user-access",
                "/expense-policy",
                "/payout-api",
                "/spend-limits",
                "/connect-api",
                "/card-issuance-api"
            ], 
            campaign: 'product' 
        },
        { slugs: ["/rewards", ], campaign: 'rewards' }
    ];

    const excludedCountries = ['SG', 'ID', 'HK', 'MY', 'CN', 'TH', 'PH', 'VN'];

    // Select all links with the specified data attributes
    // const targetElements = document.querySelectorAll('[is-set-utm-params="true"], [data-utm-params-in-url="true"], [is-get-all-params="true"], [data-cta-position="get-started-nav"], [data-cta-position="get-started-nav-mob"], [data-cta-position="get-started-stick-nav-mob"]');
    const targetElements = document.querySelectorAll('[is-set-utm-params="true"]');

    


    // Get UTM parameters from the URL
    const utmSource = getUrlParameter('utm_source');
    const utmTerm = getUrlParameter('utm_term');

    // Constants for known search engines
    const searchEngines = [
        "google", "bing", "yahoo", "duckduckgo", "yandex",
        "ecosia.org", "aol", "baidu", "msn", "so.com",
        "naver", "qwant.com", "startsiden", "360.cn",
        "seznam", "sogou", "centrum", "chatgpt",
        "amazon", "amazonaws", "connect.stripe.com", "youtube.com",
        "so","qwant","360","stripe","youtube"
    ];

    // Constants for homepage slugs
    const homepageSlugs = [
        "/", 
        "/zh-SG", 
        "/id", 
        "/id-ID", 
        "/hk", 
        "/zh-HK", 
        "/zh-Hans-HK",
    ];
    // Get the current pathname
    const currentPath = window.location.pathname;

    // Get the base referrer domain from the document
    const referrerDomain = document.referrer ? new URL(document.referrer).hostname : '';
    const baseReferrerDomain = referrerDomain 
        ? referrerDomain.split('.').slice(-2, -1)[0].toLowerCase() // Get the second-to-last segment
        : ''; // Fallback to an empty string if no referrer

    console.log(baseReferrerDomain ? `Base Referrer Domain: ${baseReferrerDomain}` : 'No referrer domain found.');

    // Function to retrieve a URL parameter by name
    function getUrlParameter(name) {
        const urlParams = new URLSearchParams(window.location.search);
        const value = urlParams.get(name);
        // console.log(`Retrieved URL parameter: ${name} = ${value}`);
        return value;
    }


    // Function to retrieve the country code of the visitor
    function getVisitorCountryCode() {
        // Get the current pathname
        const currentPath = window.location.pathname;
        console.log("Current Path:", currentPath);
    
        // Mapping of path conditions to corresponding GTM IDs
        const gtmMapping = {
            '/id': 'GTM-MH4PDH2',
            '/id-ID': 'GTM-MH4PDH2',
            '/hk': 'GTM-NW7C3NMD',
            '/zh-HK': 'GTM-NW7C3NMD',
            '/zh-Hans-HK': 'GTM-NW7C3NMD',
            '/zh-SG': 'GTM-NNQBB6W', // Added condition for /zh-SG
        };
    
        // Default GTM ID
        const gtmId = gtmMapping[Object.keys(gtmMapping).find(path => currentPath.includes(path))] || 'GTM-NNQBB6W';
    
        // Attempt to get the country code using the determined GTM ID
        const countryCode = google_tag_manager?.[gtmId]?.dataLayer?.get('visitorApiCountryCode') || 'PRIVATE';
    
        console.log('Visitor Country Code:', countryCode);
        return countryCode;
    }



    // Function to set UTM parameters in the URL of links
    function setUTMParamsInUrl() {


        // Always add country
        // Retrieve the visitor country code
        const visitorCountryCode = getVisitorCountryCode();
    
        // Prepare a new object for valid UTM parameters
        
    
        // Check if the visitor country code is part of the allowed countries
        
        if (excludedCountries.includes(visitorCountryCode)) {
            validUTMParams.country = visitorCountryCode; // Add country parameter if valid
            // console.log(`Adding country parameter: country=${visitorCountryCode}`);
        } 
    
        // Check if UTM aspireapp_params cookie is set; if true, use cookie values
        if (isAspireAppParamsCookieSet()) {
            console.log("Using aspireapp_params from cookies.");
            
            // Populate validUTMParams from cookies
            const cookieParams = getAspireAppParamsObject();
            console.log("cookieParams:", cookieParams);
            // Filter out empty or null UTM parameters from cookies
            Object.entries(cookieParams).forEach(([key, value]) => {
                if (value) { // Only include parameters that are not null or empty
                    validUTMParams[key] = value;
                }
            });
            console.log("validUTMParams:", validUTMParams)
        } else {
            console.log("Using aspireapp_params from CURRENT URL.");

            const currentUrlParams = getAllUrlParams();
            // If no cookie is set, use the current validUTMParams (these are the params from current URL)
            Object.entries(currentUrlParams).forEach(([key, value]) => {
                if (value) { // Only include parameters that are not null or empty
                    validUTMParams[key] = value;
                }
            });

        }
    
        // Loop through each link and set the URL parameters
        targetElements.forEach(element => {
            if (element.tagName.toLowerCase() === 'a') {
                // If it's a link, update the href attribute
                const currentUrl = new URL(element.href);
                const urlParams = new URLSearchParams(currentUrl.search);
    
                // Update or add valid UTM parameters
                Object.entries(validUTMParams).forEach(([key, value]) => {
                    if (value) { // Only update if the value is not null or empty
                        urlParams.set(key, value); // This will add or update the parameter
                    }
                });
    
                currentUrl.search = urlParams.toString(); // Set the updated search/query part
                element.href = currentUrl.toString(); // Update the href attribute
                console.log(`Updated link: ${element.href}`);
            }
        });

    }
    

        
    // Function to clear UTM cookies
    function clearUTMCookies() {
        // List of cookie names to clear
        const cookieNames = ['aspireapp_params'];

        // Loop through the cookie names and set their expiration date to the past
        cookieNames.forEach(name => {
            document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
        });
    }


    // Function to retrieve parameters from the URL and save them to a cookie
    function saveUrlParamsToCookie() {

        const urlParams = new URLSearchParams(window.location.search);
        let paramArray = [];

        // Update or add valid UTM parameters
        Object.entries(validUTMParams).forEach(([key, value]) => {
            if (value) { // Only update if the value is not null or empty
                paramArray.push(`${key}=${value}`);
            }
        });

        const paramString = paramArray.join(','); // Use ',' as the delimiter
        setMultipleParamsCookie(paramString); // Set the cookie with the parameter string
    }

    // Function to set a cookie with multiple parameters
    function setMultipleParamsCookie(paramString) {
        const expires = new Date(Date.now() + (30 * 24 * 60 * 60 * 1000)).toUTCString(); // 30 days expiration
        document.cookie = `aspireapp_params=${paramString}; expires=${expires}; path=/`;
        console.log(`Cookie set: aspireapp_params=${paramString}, expires in 30 days.`);
    }


    // Function to check if the aspireapp_params cookie is set
    function isAspireAppParamsCookieSet() {
        const cookieValue = document.cookie.split('; ').find(row => row.startsWith('aspireapp_params='));
        
        if (cookieValue) {
            console.log("aspireapp_params cookie is present.");
            return true; // Cookie is set
        }
        
        console.log("aspireapp_params cookie not found.");
        return false; // Cookie is not set
    }

    // Function to retrieve all URL parameters and save them as an object, excluding empty ones
    function getAllUrlParams() {
        const urlParams = new URLSearchParams(window.location.search);
        const paramsObject = {};

        urlParams.forEach((value, key) => {
            if (value) { // Only add to the object if the value is not empty
                paramsObject[key] = value;
            }
        });

        console.log('Extracted Parameters Object:', paramsObject);
        return paramsObject; // Return the populated object
    }


    // Function to get the value of aspireapp_params cookie and convert it to an object
    function getAspireAppParamsObject() {
        const cookieValue = document.cookie.split('; ').find(row => row.startsWith('aspireapp_params='));
        if (!cookieValue) {
            console.log("aspireapp_params cookie not found.");
            return {}; // Return an empty object if the cookie is not set
        }
    
        // Remove the "aspireapp_params=" prefix
        const paramsString = cookieValue.slice(cookieValue.indexOf('=') + 1); // Get the substring after '='
    
        // Split the parameters string into individual key-value pairs
        const paramsArray = paramsString.split(',');
    
        // Create an object to hold the key-value pairs
        const paramsObject = {};
        
        // Populate the object with key-value pairs
        paramsArray.forEach(param => {
            const [key, value] = param.split('=');
            if (key && value) {
                paramsObject[key.trim()] = value.trim(); // Trim spaces and add to the object
            }
        });
    
        console.log("Extracted Parameters Object:", paramsObject); // Logging the resultant object
        return paramsObject; // Return the populated object
    }

    // Function to check if any parameters exist in the current URL
    function hasUrlParameters() {
        const urlParams = new URLSearchParams(window.location.search);
        
        // Check if there are any parameters
        const hasParams = Array.from(urlParams).length > 0;

        // Logging the result
        if (hasParams) {
            console.log("URL has parameters:", urlParams.toString());
        } else {
            console.log("No URL parameters found.");
        }

        return hasParams; // Return true if parameters exist, false otherwise
    }

    // Function to check if the referrer domain is in the list of search engines
    function isReferrerInSearchEngines(domain) {
        const isKnownSearchEngine = searchEngines.includes(domain);
        console.log(`Referrer domain "${domain}" is ${isKnownSearchEngine ? '' : 'not '}in the search engines list.`);
        return isKnownSearchEngine; // Returns true if the referrer domain is a known search engine, false otherwise
    }

    function applyConditionsOnParams(){
        console.log("Scenario: User came from organic search");
        
        // Set UTM term based on specific rules
        if (homepageSlugs.includes(currentPath)) {
            validUTMParams.utm_term = "homepage"; // Set UTM term to "homepage" if current path matches any in the array
            console.log('Setting UTM Term to "homepage" since URL matches a specified slug.');
        } else {
            //if utm_term is not present in the URL
            // Proceed to get the last slug for UTM term if it does not match the specified slugs
            if(!utmTerm){
                validUTMParams.utm_term = currentPath.split('/').pop(); // Get the last slug segment
            }
        }

        console.log("Checking for campaign conditions based on current URL path:", currentPath);
        
        /// Define an array of prefixes to check
        const prefixSlugs = ["/zh-SG", "/id", "/id-ID", "/hk", "/zh-HK", "/zh-Hans-HK"];

        // Determine if currentPath matches any prefix and set effectivePath
        const isPrefixMatch = prefixSlugs.some(prefix => currentPath.startsWith(prefix));
        const effectivePath = isPrefixMatch 
            ? currentPath.replace(new RegExp(`^(${prefixSlugs.join('|')})`), '') 
            : currentPath;

        // Check if the last segment matches any of the prefixes
        const lastSegmentMatchesPrefix = prefixSlugs.some(prefix => currentPath.endsWith(prefix));

        if (lastSegmentMatchesPrefix) {
            validUTMParams.utm_campaign = 'product';
            console.log(`Setting UTM campaign to: product (last segment matched a prefix)`);
        } else {
            // Check for matching campaign conditions
            const matchedCondition = slugConditions.find(condition => 
                condition.slugs.some(slug => effectivePath.includes(slug))
            );

            validUTMParams.utm_campaign = matchedCondition ? matchedCondition.campaign : 'others';
            console.log(`Setting UTM campaign to: ${validUTMParams.utm_campaign}`);
        }
        if (isReferrerInSearchEngines(baseReferrerDomain)) {
            validUTMParams.utm_source = baseReferrerDomain;
            validUTMParams.utm_medium = 'organic';
        } else {
            validUTMParams.utm_source =  'direct';
        }
    }

    

    if((!hasUrlParameters() && !isAspireAppParamsCookieSet() && !isReferrerInSearchEngines(baseReferrerDomain))){
        // any parameter: 0
        // baseReferrerDomain in list: 0
        // cookies set: 0
        // utm_source =  1 || 0
        console.log("Scenario 1: User directly type url in browser")
        
        setUTMParamsInUrl();
        saveUrlParamsToCookie();
        return
    }

    if(!hasUrlParameters()){
        if((isReferrerInSearchEngines(baseReferrerDomain))){
            console.log("Scenario 2: User came from VALID Searchengine with NO Params")
            // any parameter: 0
            // cookies set: 0
            // baseReferrerDomain in list: 1
            // utm_source =  1 || 0
            applyConditionsOnParams();
            setUTMParamsInUrl(); // Directly call the function to set UTM parameters in all applicable elements
            saveUrlParamsToCookie();
            return; // Exit early
        }else if((!isReferrerInSearchEngines(baseReferrerDomain))){
            if(isAspireAppParamsCookieSet()){
                console.log("Scenario 3: User is navigating the site after 1st land")
                // any parameter: 0 
                // cookies set: 1
                // baseReferrerDomain in list: 1 || 0
                // utm_source =  1 || 0
                setUTMParamsInUrl(); // Directly call the function to set UTM parameters in all applicable elements
                return; // Exit early
            }else{
                console.log("Scenario 4: User visit the site directly WITHOUT any parameters")
                // any parameter: 0 Note: no need to save to cookies
                // cookies set: 1
                // baseReferrerDomain in list: 1 || 0
                // utm_source =  1 || 0
                setUTMParamsInUrl(); // Directly call the function to set UTM parameters in all applicable elements
                saveUrlParamsToCookie();
                return; // Exit early
            }
        }

        
    }
    
    if (hasUrlParameters()) {
        if (!isReferrerInSearchEngines(baseReferrerDomain)){
            console.log("Scenario 5: User came with any parameters and baseReferrerDomain NOT in the list. So use URL Params WITHOUT params conditions.")
            // any parameter: 1
            // baseReferrerDomain in list: 0
            // cookies set: 1 || 0 (if any parameter is present, need to clear cookies)
            // utm_source =  1 || 0

        }else if (isReferrerInSearchEngines(baseReferrerDomain)){

            if(!utmSource){
                console.log("Scenario 6: User came with any parameters and baseReferrerDomain is IN the list. So use URL Params WITH params conditions.")
                
                // any parameter: 1
                // baseReferrerDomain in list: 1 (apply parameter conditions)
                // cookies set: 1 || 0 (if any parameter is present, need to clear cookies)
                // utm_source: 0
                applyConditionsOnParams();
            }

        }
        clearUTMCookies();
        setUTMParamsInUrl();
        saveUrlParamsToCookie();
        return
    }
    
    
}


// Call the function on page load to execute UTM parameter handling
setTimeout(function(){
    // added 1.5 sec delay because sometimes google_tag_manager take some time to load.
    storeUTMParameters();
},0)
Editor is loading...
Leave a Comment