Countly

Countly

Source:

Countly object to manage the internal queue and send requests to Countly server. More information on https://resources.count.ly/docs/countly-sdk-for-web

Example

SDK integration

<script type="text/javascript">

//some default pre init
var Countly = Countly || {};
Countly.q = Countly.q || [];

//provide your app key that you retrieved from Countly dashboard
Countly.app_key = "YOUR_APP_KEY";

//provide your server IP or name. Use try.count.ly for EE trial server.
//if you use your own server, make sure you have https enabled if you use
//https below.
Countly.url = "https://yourdomain.com";

//start pushing function calls to queue
//track sessions automatically
Countly.q.push(["track_sessions"]);

//track sessions automatically
Countly.q.push(["track_pageview"]);

//load countly script asynchronously
(function() {
 var cly = document.createElement("script"); cly.type = "text/javascript";
 cly.async = true;
 //enter url of script here
 cly.src = "https://cdn.jsdelivr.net/countly-sdk-web/latest/countly.min.js";
 cly.onload = function(){Countly.init()};
 var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(cly, s);
})();
</script>

Namespaces

_internals
userData

Members

(static) CountlyClass

Source:

Countly class - exposing so plugins can extend its prototype

(static) DeviceIdType

Source:
Properties:
Name Type Description
DEVELOPER_SUPPLIED
SDK_GENERATED
TEMPORARY_ID

Possible device Id types are: DEVELOPER_SUPPLIED, SDK_GENERATED, TEMPORARY_ID

(static) onload

Source:

Array of functions that are waiting to be notified that script has loaded and instantiated

Example
Countly.onload.push(function(){
     console.log("script loaded");
 });

(static) q

Source:

Async api queue, push commands here to be executed when script is loaded or after

Example

Add command as array

 Countly.q.push(['add_event',{
     key:"asyncButtonClick",
     segmentation: {
         "id": ob.id
     }
 }]);

Methods

(static) deserialize(data) → {varies}

Source:

Overwrite deserialization function for extending SDK with encryption, etc

Parameters:
Name Type Description
data string

value to deserialize

Returns:

deserialized value

Type
varies

(static) getSearchQuery() → {string}

Source:

Overwrite a way to get search query

Returns:

view url

Type
string

(static) getViewName() → {string}

Source:

Overwrite a way to retrieve view name

Returns:

view name

Type
string

(static) getViewUrl() → {string}

Source:

Overwrite a way to retrieve view url

Returns:

view url

Type
string

(static) init(conf) → {Object}

Source:
Deprecated:
  • {number} [conf.max_logs=100] - maximum amount of breadcrumbs to store for crash logs

Initialize Countly object

Example
Countly.init({
  //provide your app key that you retrieved from Countly dashboard
  app_key: "YOUR_APP_KEY",
  //provide your server IP or name. Use try.count.ly for EE trial server.
  url: "http://yourdomain.com"
});
Parameters:
Name Type Description
conf Object

Countly initialization Init object with configuration options

Properties
Name Type Attributes Default Description
app_key string

app key for your app created in Countly

device_id string

to identify a visitor, will be auto generated if not provided

url string

your Countly server url, you can use your server URL or IP here

clear_stored_id boolean <optional>
false

set it to true if you want to erase previously stored device ID from the local storage

app_version string <optional>
0.0

the version of your app or website

country_code string <optional>

country code for your visitor

city string <optional>

name of the city of your visitor

ip_address string <optional>

ip address of your visitor

debug boolean <optional>
false

output debug info into console

ignore_bots boolean <optional>
true

option to ignore traffic from bots

interval number <optional>
500

set an interval how often to check if there is any data to report and report it in milliseconds

queue_size number <optional>
1000

maximum amount of queued requests to store

fail_timeout number <optional>
60

set time in seconds to wait after failed connection to server in seconds

inactivity_time number <optional>
20

after how many minutes user should be counted as inactive, if he did not perform any actions, as mouse move, scroll or keypress

session_update number <optional>
60

how often in seconds should session be extended

max_events number <optional>
100

maximum amount of events to send in one batch

max_key_length number <optional>
128

maximum size of all string keys

max_value_size number <optional>
256

maximum size of all values in our key-value pairs (Except "picture" field, that has a limit of 4096 chars)

max_segmentation_values number <optional>
30

max amount of custom (dev provided) segmentation in one event

max_breadcrumb_count number <optional>
100

maximum amount of breadcrumbs that can be recorded before the oldest one is deleted

max_stack_trace_lines_per_thread number <optional>
30

maximum amount of stack trace lines would be recorded per thread

max_stack_trace_line_length number <optional>
200

maximum amount of characters are allowed per stack trace line. This limits also the crash message length

ignore_referrers array <optional>

array with referrers to ignore

ignore_prefetch boolean <optional>
true

ignore prefetching and pre rendering from counting as real website visits

rc_automatic_optin_for_ab boolean <optional>
true

opts in the user for A/B testing while fetching the remote config (if true)

use_explicit_rc_api boolean <optional>
false

set it to true to use the new remote config API

force_post boolean <optional>
false

force using post method for all requests

ignore_visitor boolean <optional>
false

ignore this current visitor

require_consent boolean <optional>
false

Pass true if you are implementing GDPR compatible consent management. It would prevent running any functionality without proper consent

utm boolean <optional>
{"source":true, "medium":true, "campaign":true, "term":true, "content":true}

Object instructing which UTM parameters to track

use_session_cookie boolean <optional>
true

Use cookie to track session

enable_orientation_tracking boolean <optional>
true

Enables orientation tracking at the start of a session

heatmap_whitelist array <optional>
[]

array with trustable domains for heatmap reporting

session_cookie_timeout number <optional>
30

How long till cookie session should expire in minutes

remote_config boolean | function <optional>
false

Enable automatic remote config fetching, provide callback function to be notified when fetching done

namespace string <optional>
""

Have separate namespace of of persistent data

track_domains boolean <optional>
true

Set to false to disable domain tracking, so no domain data would be reported

metrics Object <optional>
{}

provide metrics for this user, or else will try to collect what's possible

Properties
Name Type Description
_os string

name of platform/operating system

_os_version string

version of platform/operating system

_device string

device name

_resolution string

screen resolution of the device

_carrier string

carrier or operator used for connection

_density string

screen density of the device

_locale string

locale or language of the device in ISO format

_store string

source from where the user came from

_browser string

browser name

_browser_version string

browser version

_ua string

user agent string

headers Object <optional>
{}

Object to override or add headers to all SDK requests

storage string <optional>
default

What type of storage to use, by default uses local storage and would fallback to cookies, but you can set values "localstorage" or "cookies" to force only specific storage, or use "none" to not use any storage and keep everything in memory

Returns:

countly tracker instance

Type
Object

(static) serialize(value) → {string}

Source:

Overwrite serialization function for extending SDK with encryption, etc

Parameters:
Name Type Description
value any

value to serialize

Returns:

serialized value

Type
string
Source:

Add consent for specific feature, meaning, user allowed to track that data (either core feature of from custom feature group)

Parameters:
Name Type Description
feature string | array

name of the feature, possible values, "sessions","events","views","scrolls","clicks","forms","crashes","attribution","users", etc or custom provided through Countly.group_features

add_event(event)

Source:

Report custom event

Parameters:
Name Type Description
event Object

Countly Event object

Properties
Name Type Attributes Default Description
key string

name or id of the event

count number <optional>
1

how many times did event occur

sum number <optional>

sum to report with event (if any)

dur number <optional>

duration to report with event (if any)

segmentation Object <optional>

object with segments key /values

add_log(record)

Source:

Add new line in the log of breadcrumbs of what user did, will be included together with error report

Parameters:
Name Type Description
record string

any text describing what user did

begin_session(noHeartBeat, force)

Source:

Start session

Parameters:
Name Type Description
noHeartBeat boolean

true if you don't want to use internal heartbeat to manage session

force bool

force begin session request even if session cookie is enabled

cancel_event(key) → {boolean}

Source:

Cancel timed event, cancels a timed event if it exists

Parameters:
Name Type Description
key string

event name that will canceled

Returns:
  • returns true if the event was canceled and false if no event with that key was found
Type
boolean

change_id(newId, merge)

Source:

Change current user/device id

Parameters:
Name Type Description
newId string

new user/device ID to use. Must be a non-empty string value. Invalid values (like null, empty string or undefined) will be rejected

merge boolean

move data from old ID to new ID on server

Source:

Check if any consent is given, for some cases, when crucial parts are like device_id are needed for any request

Returns:

true is has any consent given, false if no consents given

Type
Boolean
Source:

Check if consent is given for specific feature (either core feature of from custom feature group)

Parameters:
Name Type Description
feature string

name of the feature, possible values, "sessions","events","views","scrolls","clicks","forms","crashes","attribution","users" or custom provided through Countly.group_features

Returns:

true if consent was given for the feature or false if it was not

Type
Boolean

collect_from_facebook(customopt)

Source:

Collect information about user from Facebook, if your website integrates Facebook SDK. Call this method after Facebook SDK is loaded and user is authenticated.

Parameters:
Name Type Attributes Description
custom Object <optional>

Custom keys to collected from Facebook, key will be used to store as key in custom user properties and value as key in Facebook graph object. For example, {"tz":"timezone"} will collect Facebook's timezone property, if it is available and store it in custom user's property under "tz" key. If you want to get value from some sub object properties, then use dot as delimiter, for example, {"location":"location.name"} will collect data from Facebook's {"location":{"name":"MyLocation"}} object and store it in user's custom property "location" key

collect_from_forms(parentopt, useCustomopt)

Source:

Collect possible user data from submitted forms. Add cly_user_ignore class to ignore inputs in forms or cly_user_{key} to collect data from this input as specified key, as cly_user_username to save collected value from this input as username property. If not class is provided, Countly SDK will try to determine type of information automatically.

Parameters:
Name Type Attributes Default Description
parent Object <optional>

DOM object which children to track, by default it is document body

useCustom boolean <optional>
false

submit collected data as custom user properties, by default collects as main user properties

enable_feedback(paramsopt)

Source:
Deprecated:
  • use 'enableRatingWidgets' in place of this call

Show rating widget popup by passed widget ids array

Parameters:
Name Type Attributes Description
params object <optional>

required - includes "popups" property as string array of widgets ("widgets" for old versions) example params: {"popups":["5b21581b967c4850a7818617"]}

enableRatingWidgets(paramsopt)

Source:

Show rating widget popup by passed widget ids array

Parameters:
Name Type Attributes Description
params object <optional>

required - includes "popups" property as string array of widgets ("widgets" for old versions) example params: {"popups":["5b21581b967c4850a7818617"]}

end_event(event)

Source:

End timed event

Parameters:
Name Type Description
event string | object

event key if string or Countly event same as passed to Countly.add_event

end_session(sec, force)

Source:

End current session

Parameters:
Name Type Description
sec int

amount of seconds to report for current session, before ending it

force bool

force end session request even if session cookie is enabled

enrollUserToAb(keysopt)

Source:

AB testing key provider, opts the user in for the selected keys

Parameters:
Name Type Attributes Description
keys array <optional>

Array of keys opt in FOR

fetch_remote_config(keysopt, omit_keysopt, callbackopt)

Source:

Fetch remote config from the server (old one for method=fetch_remote_config API)

Parameters:
Name Type Attributes Description
keys array <optional>

Array of keys to fetch, if not provided will fetch all keys

omit_keys array <optional>

Array of keys to omit, if provided will fetch all keys except provided ones

callback function <optional>

Callback to notify with first param error and second param remote config object

get_available_feedback_widgets(callback)

Source:

This function retrieves all associated widget information (IDs, type, name etc in an array/list of objects) of your app

Parameters:
Name Type Description
callback function

Callback function with two parameters, 1st for returned list, 2nd for error

get_device_id() → {string}

Source:

Gets the current device id

Returns:

device id

Type
string

get_device_id_type() → {number}

Source:

Check and return the current device id type

Returns:

a number that indicates the device id type

Type
number

get_remote_config(keyopt) → {object}

Source:

Gets remote config object (all key/value pairs) or specific value for provided key from the storage

Parameters:
Name Type Attributes Description
key string <optional>

if provided, will return value for key, or return whole object

Returns:

remote configs

Type
object

getFeedbackWidgetData(CountlyFeedbackWidget, callback)

Source:

Get feedback (nps, survey or rating) widget data, like questions, message etc.

Parameters:
Name Type Description
CountlyFeedbackWidget Object

Widget object, retrieved from 'get_available_feedback_widgets'

callback function

Callback function with two parameters, 1st for returned widget data, 2nd for error

group_features(features)

Source:

Modify feature groups for consent management. Allows you to group multiple features under one feature group

Examples

Adding all features under one group

Countly.group_features({all:["sessions","events","views","scrolls","clicks","forms","crashes","attribution","users"]});
//After this call Countly.add_consent("all") to allow all features
        

Grouping features

Countly.group_features({
   activity:["sessions","events","views"],
   interaction:["scrolls","clicks","forms"]
});
//After this call Countly.add_consent("activity") to allow "sessions","events","views"
//or call Countly.add_consent("interaction") to allow "scrolls","clicks","forms"
//or call Countly.add_consent("crashes") to allow some separate feature
Parameters:
Name Type Description
features object

object to define feature name as key and core features as value

halt()

Source:

WARNING!!! Should be used only for testing purposes!!!

Resets Countly to its initial state (used mainly to wipe the queues in memory). Calling this will result in a loss of data

initialize_feedback_popups(enableWidgetsopt)

Source:
Deprecated:
  • use 'initializeRatingWidgets' in place of this call

Prepare rating widgets according to the current options

Parameters:
Name Type Attributes Description
enableWidgets array <optional>

widget ids array

initializeRatingWidgets(enableWidgetsopt)

Source:

Prepare rating widgets according to the current options

Parameters:
Name Type Attributes Description
enableWidgets array <optional>

widget ids array

log_error(err, segmentsopt)

Source:

Log an exception that you caught through try and catch block and handled yourself and just want to report it to server

Parameters:
Name Type Attributes Description
err Object

error exception object provided in catch block

segments string <optional>

additional key value pairs you want to provide with error report, like versions of libraries used, etc.

onStorageChange(key, newValue)

Source:

Apply modified storage changes

Parameters:
Name Type Description
key String

key of storage modified

newValue Varies

new value for storage

opt_in()

Source:

Opts in user for tracking, if complies with other user ignore rules like bot useragent and prefetch settings

opt_out()

Source:

Opts out user of any metric tracking

present_feedback_widget(presentableFeedback, id, className)

Source:

Present the feedback widget in webview

Parameters:
Name Type Description
presentableFeedback Object

Current presentable feedback

id String

DOM id to append the feedback widget

className String

Class name to append the feedback widget

presentRatingWidgetWithID(id)

Source:

Show specific widget popup by the widget id

Parameters:
Name Type Description
id string

id value of related rating widget, you can get this value by click "Copy ID" button in row menu at "Feedback widgets" screen

recordDirectAttribution(campaign_idopt, campaign_user_idopt)

Source:

Report user conversion to the server (when user signup or made a purchase, or whatever your conversion is), if there is no campaign data, user will be reported as organic

Parameters:
Name Type Attributes Description
campaign_id string <optional>

id of campaign, or will use the one that is stored after campaign link click

campaign_user_id string <optional>

id of user's click on campaign, or will use the one that is stored after campaign link click

recordError(err, nonfatal, segments)

Source:

Record and report error, this is were tracked errors are modified and send to the request queue

Parameters:
Name Type Description
err Error

Error object

nonfatal Boolean

nonfatal if true and false if fatal

segments Object

custom crash segments

recordRatingWidgetWithID(ratingWidget)

Source:

Provide information about user

Parameters:
Name Type Description
ratingWidget Object

object with rating widget properties

Properties
Name Type Attributes Description
widget_id string

id of the widget in the dashboard

contactMe boolean <optional>

did user give consent to contact him

platform string <optional>

user's platform (will be filled if not provided)

app_version string <optional>

app's app version (will be filled if not provided)

rating number

user's rating from 1 to 5

email string <optional>

user's email

comment string <optional>

user's comment

Source:

Remove consent for specific feature, meaning, user opted out to track that data (either core feature of from custom feature group)

Parameters:
Name Type Description
feature string | array

name of the feature, possible values, "sessions","events","views","scrolls","clicks","forms","crashes","attribution","users", etc or custom provided through Countly.group_features

enforceConsentUpdate Boolean

regulates if a request will be sent to the server or not. If true, removing consents will send a request to the server and if false, consents will be removed without a request

report_conversion(campaign_idopt, campaign_user_idopt)

Source:
Deprecated:
  • use 'recordDirectAttribution' in place of this call

Report user conversion to the server (when user signup or made a purchase, or whatever your conversion is), if there is no campaign data, user will be reported as organic

Parameters:
Name Type Attributes Description
campaign_id string <optional>

id of campaign, or will use the one that is stored after campaign link click

campaign_user_id string <optional>

id of user's click on campaign, or will use the one that is stored after campaign link click

report_feedback(ratingWidget)

Source:
Deprecated:
  • use 'recordRatingWidgetWithID' in place of this call

Provide information about user

Parameters:
Name Type Description
ratingWidget Object

object with rating widget properties

Properties
Name Type Attributes Description
widget_id string

id of the widget in the dashboard

contactMe boolean <optional>

did user give consent to contact him

platform string <optional>

user's platform (will be filled if not provided)

app_version string <optional>

app's app version (will be filled if not provided)

rating number

user's rating from 1 to 5

email string <optional>

user's email

comment string <optional>

user's comment

report_orientation(orientationopt)

Source:

Report device orientation

Parameters:
Name Type Attributes Description
orientation string <optional>

orientation as landscape or portrait

report_trace(trace)

Source:

Report performance trace

Parameters:
Name Type Description
trace Object

apm trace object

Properties
Name Type Attributes Description
type string

device or network

name string

url or view of the trace

stz number

start timestamp

etz number

end timestamp

app_metrics Object

key/value metrics like duration, to report with trace where value is number

apm_attr Object <optional>

object profiling attributes (not yet supported)

reportFeedbackWidgetManually(CountlyFeedbackWidget, CountlyWidgetData, widgetResult)

Source:

Report information about survey, nps or rating widget answers/results

Parameters:
Name Type Description
CountlyFeedbackWidget Object

it is the widget object retrieved from get_available_feedback_widgets

CountlyWidgetData Object

it is the widget data object retrieved from getFeedbackWidgetData

widgetResult Object

it is the widget results that need to be reported, different for all widgets, if provided as null it means the widget was closed widgetResult For NPS Should include rating and comment from the nps. Example: widgetResult = {rating: 3, comment: "comment"}

widgetResult For Survey Should include questions ids and their answers as key/value pairs. Keys should be formed as “answ-”+[question.id]. Example: widgetResult = { "answ-1602694029-0": "Some text field long answer", //for text fields "answ-1602694029-1": 7, //for rating "answ-1602694029-2": "ch1602694029-0", //There is a question with choices like multi or radio. It is a choice key. "answ-1602694029-3": "ch1602694030-0,ch1602694030-1" //In case 2 selected }

widgetResult For Rating Widget Should include rating, email, comment and contact consent information. Example: widgetResult = { rating: 2, email: "email@mail.com", contactMe: true,
comment: "comment" }

session_duration(sec)

Source:

Report session duration

Parameters:
Name Type Description
sec int

amount of seconds to report for current session

show_feedback_popup(id)

Source:
Deprecated:
  • use 'presentRatingWidgetWithID' in place of this call

Show specific widget popup by the widget id

Parameters:
Name Type Description
id string

id value of related rating widget, you can get this value by click "Copy ID" button in row menu at "Feedback widgets" screen

start_event(key)

Source:

Start timed event, which will fill in duration property upon ending automatically This works basically as a timer and does not create an event till end_event is called

Parameters:
Name Type Description
key string

event name that will be used as key property

start_time()

Source:

Start tracking duration time for this user, by default it is automatically tracked if you are using internal session handling

stop_time()

Source:

Stop tracking duration time for this user

track_clicks(parentopt)

Source:

Track all clicks on this page

Parameters:
Name Type Attributes Description
parent Object <optional>

DOM object which children to track, by default it is document body

track_errors(segmentsopt)

Source:

Automatically track javascript errors that happen on the website and report them to the server

Parameters:
Name Type Attributes Description
segments string <optional>

additional key value pairs you want to provide with error report, like versions of libraries used, etc.

track_forms(parentopt, trackHiddenopt)

Source:

Generate custom event for all forms that were submitted on this page

Parameters:
Name Type Attributes Description
parent Object <optional>

DOM object which children to track, by default it is document body

trackHidden boolean <optional>

provide true to also track hidden inputs, default false

Source:

Generate custom event for all links that were clicked on this page

Parameters:
Name Type Attributes Description
parent Object <optional>

DOM object which children to track, by default it is document body

track_pageview(pageopt, ignoreListopt, viewSegmentsopt)

Source:

Track page views user visits

Parameters:
Name Type Attributes Description
page string <optional>

optional name of the page, by default uses current url path

ignoreList array <optional>

optional array of strings or regexps to test for the url/view name to ignore and not report

viewSegments object <optional>

optional key value object with segments to report with the view

track_scrolls(parentopt)

Source:

Track all scrolls on this page

Parameters:
Name Type Attributes Description
parent Object <optional>

DOM object which children to track, by default it is document body

track_sessions()

Source:

Track user sessions automatically, including time user spent on your website

track_view(pageopt, ignoreListopt, segmentsopt)

Source:

Track page views user visits. Alias of track_pageview method for compatibility with NodeJS SDK

Parameters:
Name Type Attributes Description
page string <optional>

optional name of the page, by default uses current url path

ignoreList array <optional>

optional array of strings or regexps to test for the url/view name to ignore and not report

segments object <optional>

optional view segments to track with the view

user_details(user)

Source:

Provide information about user

Parameters:
Name Type Description
user Object

Countly UserDetails object

Properties
Name Type Attributes Description
name string <optional>

user's full name

username string <optional>

user's username or nickname

email string <optional>

user's email address

organization string <optional>

user's organization or company

phone string <optional>

user's phone number

picture string <optional>

url to user's picture

gender string <optional>

M value for male and F value for female

byear number <optional>

user's birth year used to calculate current age

custom Object <optional>

object with custom key value properties you want to save with user