Countly Web SDK

repository·master·Indexed 42 days ago

https://github.com/countly/countly-sdk-web

A client-side library for integrating product analytics, crash reporting, A/B testing, and performance monitoring into web applications. Compatible with Countly Lite, Flex, and Enterprise server deployments, version 26.1.2 supports user profiles, feedback widgets, and remote configuration for dynamic tracking adjustments.

Tokens
16.7K
Snippets
56
Records
79
Agent score
48%

What's inside Countly

  1. Overview of Countly Web SDK

    master

    The Countly Web SDK is a client-side library designed for integration into websites and web applications. It is bundled from the modular Countly JavaScript SDK and is compatible with Countly Lite, Countly Flex, and Countly Enterprise server deployments.

    Key features supported by the SDK include:

    • Analytics: Track user behavior and product performance.
    • User Profiles: Manage and track individual user data.
    • Crash Reports: Monitor and capture application errors and crashes.
    • A/B Testing: Run experiments to optimize user experience.
    • Performance Monitoring: Track application performance metrics.
    • Feedback Widgets: Collect user feedback via surveys, NPS, and ratings.
  2. What is the Countly Google Analytics Adapter?

    master
    The Countly Google Analytics Adapter is a migration tool designed for web applications that have already implemented Google Analytics trackers. It allows you to simultaneously send your existing analytics data to your Countly instance without requiring additional integration work for your existing Google Analytics calls.
  3. Integrate Countly Web SDK into your project

    master

    To use the Countly Web SDK, you can follow the official documentation for detailed setup instructions. The SDK can be integrated using various methods depending on your project structure (e.g., via npm or direct script inclusion).

    For practical implementation, you can refer to the integration examples provided in the repository's examples directory.

  4. Generate Countly implementation examples

    master

    You can use the create_examples.py script to automatically generate boilerplate implementation examples for different frameworks. The script supports generating examples for:

    • React
    • Angular
    • Symbolication (for Web SDK)
    • All of the above

    Run the script using Python, and follow the interactive prompts to select the desired example type.

    python create_examples.py
    # or
    python3 create_examples.py
  5. Implement the Countly Google Analytics Adapter

    master

    To migrate your Google Analytics data to Countly, follow these three steps:

    1. Integrate the Countly Web SDK: Add the Countly initialization snippet to your web page. You must provide your Countly.app_key and your Countly.url.
    2. Load the Adapter: Declare the ga_adapter.js script after the Countly SDK has been integrated.
    3. Initialize the Adapter: Call CountlyGAAdapter() within your existing Google Analytics configuration block.
    // 1. Countly SDK Integration
    <script type='text/javascript'>
    var Countly = Countly || {};
    Countly.q = Countly.q || [];
    Countly.onload = Countly.onload || [];
    Countly.app_key = "YOUR_APP_KEY";
    Countly.url = "https://yourdomain.com"; 
    
    Countly.q.push(['track_sessions']);
    Countly.q.push(['track_pageview']);
    
    (function() {
     var cly = document.createElement('script'); cly.type = 'text/javascript'; 
     cly.async = true;
     cly.src = 'https://cdn.jsdelivr.net/npm/countly-sdk-web@latest/lib/countly.min.js';
     cly.onload = function(){Countly.init()};
     var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(cly, s);
    })();
    </script>
    
    // 2. Declare the adapter script
    <script src="../plugin/ga_adapter/ga_adapter.js"></script>
    
    // 3. Update Google Analytics snippet
    <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
    
    // Call the adapter
    CountlyGAAdapter();
    
    ga('create', 'UA-56295140-3', 'auto');
    ga('send','event','category','action','label');
    ga('send','pageview','page.html');
    </script>
  6. Configure Countly SDK credentials in examples

    master

    When using the provided implementation examples, you must replace the placeholder configuration values with your actual Countly credentials to ensure data is sent to your specific server.

    Specifically, update the following in the example files:

    • Replace 'YOUR_APP_KEY' with your application's unique app key.
    • Replace 'https://your.server.ly' with your Countly server URL.

    Note on file paths: If you move the examples folder away from the countly-sdk-web project root, you must verify that the paths to countly.js or any plugins (e.g., ../lib/countly.js) are correctly updated to point to the actual location of the SDK files.

  7. Manage feature consents for privacy compliance

    master

    The Countly SDK allows you to manage user consent for specific tracking features. This is useful for complying with privacy regulations like GDPR. You can group multiple core features into custom groups to simplify consent management.

    Core features include: sessions, events, views, scrolls, clicks, forms, crashes, attribution, and users.

    Workflow:

    1. Group features (Optional): Use group_features to bundle features under a single name.
    2. Check consent: Use check_consent to verify if a feature is allowed before performing sensitive operations.
    3. Grant/Revoke consent: Use add_consent or remove_consent to update the user's preference.
    // 1. Grouping features
    Countly.group_features({
      activity: ["sessions", "events", "views"],
      interaction: ["scrolls", "clicks", "forms"]
    });
    
    // 2. Granting consent to a group
    Countly.add_consent("activity");
    
    // 3. Checking consent for a specific feature
    if (Countly.check_consent("views")) {
      // perform view tracking
    }
  8. How feedback widgets and surveys are presented

    master

    Countly can automatically present feedback widgets (like NPS, surveys, or ratings) based on specific showPolicy configurations. The SDK handles the timing and display logic via iframes.

    Supported showPolicy values for surveys:

    • afterPageLoad: Shows the survey once the document.readyState is complete.
    • afterConstantDelay: Shows the survey after a fixed delay (e.g., 10000ms).
    • onAbandon: Shows the survey when the user's mouse leaves the document (mouseleave event).
    • onScrollHalfwayDown: Shows the survey when the user has scrolled at least halfway down the document height.
    • default: Shows the survey immediately.

    Widget Types:

    • survey: A multi-question interaction.
    • nps: Net Promoter Score widget.
    • rating: A simple star or numerical rating widget.
  9. Extract UTM parameters from URL

    master

    The SDK automatically parses the current URL for UTM parameters (e.g., utm_source, utm_medium) during initialization. If these parameters are found, they are automatically saved to the user's profile using the userData.set method with the prefix utm_ (e.g., utm_source).

    Additionally, the SDK looks for specific Countly-related URL parameters:

    • cly_id: Sets the comparison ID (cly_cmp_id).
    • cly_uid: Sets the comparison user ID (cly_cmp_uid).
    • cly_device_id: Sets the device ID.
  10. How Countly handles HTTP responses

    master

    The SDK validates HTTP responses to ensure data integrity. A response is considered valid if:

    1. The HTTP status code is in the successful range (2xx, specifically 200 <= statusCode < 300).
    2. The response body is a valid JSON object or JSON array, or matches the specific string "No content block found!".

    If the response is not valid JSON or the status code is outside the 2xx range, the SDK logs an error and treats the request as failed.

  11. How scroll tracking works

    master

    The SDK can automatically track user scrolling behavior to provide insights into page engagement.

    Mechanism

    1. Position Tracking: The SDK monitors the maximum scroll position (window.scrollY, document.body.scrollTop, etc.).
    2. View Processing: When a scroll view is processed, the SDK captures the current document height, width, and viewport dimensions.
    3. Event Emission: If consent for SCROLLS is granted via check_consent, the SDK emits an internal ACTION event with a scroll segmentation type. This segment includes:
      • y: The vertical scroll position plus viewport height.
      • width: Document width.
      • height: Document height.
      • view: The current URL.
      • domain: The hostname (if track_domains is enabled).

    Note: The segmentation data is subject to truncation based on SDK limit settings (SCLimitKeyLength, SCLimitValueSize, etc.) to ensure payload efficiency.