> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kameleoon.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Kameleoon.API.Core

> Reference for the Kameleoon.API.Core methods that set up the engine, collect legal consent, and run code when a condition or element is present.

This module contains functions for implementing frontend A/B testing variations without flickering. The module also includes engine initialization methods, which cover privacy laws and legal consent collection.

## enableLegalConsent

Call the `enableLegalConsent()` method after you obtain legal consent from the visitor to activate Kameleoon. This method activates Kameleoon's normal operation mode. For more information, refer to the [Consent management](https://docs.kameleoon.com/developer-docs/privacy-and-compliance/consent-management.md) article.

```javascript theme={null}
var agreedButton = Kameleoon.API.Utils.querySelectorAll("#agreed")[0];

Kameleoon.API.Utils.addEventListener(agreedButton, "mousedown", function (event) {
  Kameleoon.API.Core.enableLegalConsent();
});
```

**Arguments**

| Name | Type | Description |
| - | - | - |
| module | String | Name of the module to enable: `PRODUCT_RECOMMENDATION`, `AB_TESTING`, `PERSONALIZATION`, or `BOTH`. For example, `PRODUCT_RECOMMENDATION` executes the entry point **exclusively** with product recommendation capabilities. `AB_TESTING` enables A/B testing **and** product recommendation (unless the custom option to differentiate consent is active). `BOTH` enables all capabilities. If omitted, the method activates legal consent for all modules (`BOTH`) by default. |

> [!NOTE]
>
> A custom option is also available that allows separate management of Product Recommendation consent. When this option is active, explicitly call `enableLegalConsent("PRODUCT_RECOMMENDATION")` to activate the module. Contact the Customer Success Manager to enable this feature.

## disableLegalConsent

Call the `disableLegalConsent()` method when a visitor declines the use of Kameleoon. This method disables normal operation mode. For more information, refer to the [Consent management article](https://docs.kameleoon.com/developer-docs/privacy-and-compliance/consent-management.md).

```javascript theme={null}
var disableButton = Kameleoon.API.Utils.querySelectorAll("#disable")[0];

Kameleoon.API.Utils.addEventListener(disableButton, "mousedown", function (event) {
  Kameleoon.API.Core.disableLegalConsent();
});
```

**Arguments**

| Name | Type | Description |
| - | - | - |
| module | String | Name of the module to turn off: `AB_TESTING`, `PERSONALIZATION`, or `BOTH`. If omitted, the method turns off legal consent for all modules (`BOTH`). |

> [!NOTE]
>
> A custom option is also available that allows separate management of Product Recommendation consent. When this option is active, explicitly call `disableLegalConsent("PRODUCT_RECOMMENDATION")` to turn off the module. Contact the Customer Success Manager to enable this feature.

## enableSinglePageSupport

The `enableSinglePageSupport()` method reloads the Kameleoon engine when the active URL changes, regardless of browser page loads. Use this method for Single Page Applications (SPAs) with multiple URLs and a single initial load. Kameleoon treats each URL change as a new page, enabling URL targeting and accurate tracking of metrics like page views.

```javascript theme={null}
if (location.href.indexOf("mySPAWebsitePart") != -1) {
  Kameleoon.API.Core.enableSinglePageSupport();
}
```

> [!NOTE]
>
> Kameleoon also automatically removes all elements added to the page that use HTML IDs that begin with "kameleoonElement" or "kameleoonStyleSheet" when the SPA reloads.

## enableDynamicRefresh

The `enableDynamicRefresh()` method detects element changes and reapplies Graphic Editor modifications. This method supports SPAs that dynamically modify the DOM without URL changes or page reloads, preventing dynamic updates from removing experiments. Refer to `enableSinglePageSupport()` for other SPA types.

```javascript theme={null}
if (location.href.indexOf("cart") != -1) {
    Kameleoon.API.Core.enableDynamicRefresh();
}
```

## getConfiguration

The `getConfiguration()` method returns a reference to the Configuration object, which contains global constant values for the site's Kameleoon configuration.

```javascript theme={null}
var configuration = Kameleoon.API.Core.getConfiguration();

if (configuration.siteCode == "abcde12345") {
  document.cookie = "MyMainSite=true;";
} else if (configuration.siteCode == "12345abcdef") {
  document.cookie = "MySubSite=true;";
}
```

**Return value**

| Name | Type | Description |
| - | - | - |
| configuration | Object | Configuration object. |

## load

The `load()` method initializes the Kameleoon engine. While initialization typically occurs automatically during application file loading, you might need to make manual calls. To reload Kameleoon after each URL change in a single-page app, use `enableSinglePageSupport()` instead of watching the URL yourself.

```javascript theme={null}
Kameleoon.API.Core.load();
```

> [!NOTE]
>
> Kameleoon also automatically removes all elements added to the page that use HTML IDs that begin with "kameleoonElement" or "kameleoonStyleSheet" when the SPA reloads.

## processRedirect

The `processRedirect()` method redirects the browser to another URL, typically for split A/B experiments. Use this method instead of `window.location.href = redirectionURL;` to ensure accurate background tracking.

```javascript theme={null}
var experiment = Kameleoon.API.Experiments.getByName("RedirectExperiment");

if (experiment.associatedVariation.id == 123456) {
  Kameleoon.API.Core.processRedirect("https://www.mywebsite.com?variation=A");
}
```

> [!NOTE]
>
> If the redirection URL is on a domain other than the base URL and the Kameleoon installation omits [unified session data](https://docs.kameleoon.com/developer-docs/web-experimentation/technical-concepts/unify-session-data-storage-across-subdomains.md), the engine adds a `kameleoonRedirect-{experimentID}` parameter to the target URL to ensure accurate tracking.

**Arguments**

| Name | Type | Description |
| - | - | - |
| redirectionURL | String | URL for redirection. This field is mandatory. |

## runWhenConditionTrue

The `runWhenConditionTrue()` method executes the callback function when the `conditionFunction` returns true. The method uses a polling mechanism, which might cause flickering. Use `runWhenElementPresent()` instead for improved performance. Refer to the [`runWhenElementPresent()` description](#runwhenelementpresent) for details.

```javascript theme={null}
Kameleoon.API.Core.runWhenConditionTrue(function () {
  return typeof jQuery != "undefined";
}, function () {
  jQuery("#bloc-2345").text("Mon nouveau texte");
}, 200);
```

**Arguments**

| Name | Type | Description |
| - | - | - |
| conditionFunction | Function | JavaScript function returning **true** or **false**. This field is mandatory. |
| callback | Function | JavaScript function executing when the **conditionFunction** returns **true**. This field is mandatory. |
| pollingInterval | Number | The engine executes the **conditionFunction** periodically at this interval. When `runWhenElementPresent()` is unavailable, a lower **pollingInterval** reduces flickering but increases CPU usage. If omitted, the method defaults to **200 milliseconds**. |

## runWhenElementPresent

The `runWhenElementPresent()` method executes the callback function when a specific element appears in the DOM. This method uses mutation observers to power antiflickering technology. Identify the key elements for a variation and call `runWhenElementPresent()` with the element as the first argument and the implementation code as the callback. Calling the method ensures that modifications execute when the element appears, before the browser initiates a display refresh cycle.

To act on multiple elements, call `runWhenElementPresent()` separately for each element rather than targeting only the expected final element. A single call may result in flickering if a refresh cycle occurs between the appearance of different elements.

```javascript theme={null}
// With mutation observers management.
Kameleoon.API.Core.runWhenElementPresent("#bloc-2345", function (elements) {
 elements[0].innerText = "My new Text";
});

// With multiple CSS selectors. Executes if any one of the elements is present.
Kameleoon.API.Core.runWhenElementPresent("#bloc-567, .cta-button, #bloc-789", function (elements) {
 elements[0].innerText = "More new text";
});

// Without mutation observers management, Kameleoon polls every 200ms to check if the element is on the page.
Kameleoon.API.Core.runWhenElementPresent("#MyPopup.showed", function (elements) {
 Kameleoon.API.Events.trigger("popup displayed");
}, 200);

// With mutation observers management and Single Page App support, Kameleoon applies modifications whenever new elements are added to the DOM or when there is a dynamic refresh of the Single Page App that removes previous modifications.
Kameleoon.API.Core.runWhenElementPresent(".product-button", function (elements) {
 elements.forEach(element => {
  element.innerText = "Add To Cart";
 });
}, null, true);
```

> [!NOTE]
>
> Providing this value **disables** Mutation Observers and Anti-Flickering, reverting to legacy polling. Use this argument only in specific cases, such as complex selector queries with high CPU impact.

**Arguments**

| Name | Type | Description |
| - | - | - |
| selector | String | CSS selector of the element. To specify multiple CSS selectors, provide a single comma-separated string. The callback executes when one or more elements exist. This field is mandatory. |
| callback | Function | JavaScript function to execute when the element appears in the DOM. This field is mandatory. |
| pollingInterval | Number | Providing this value disables Mutation Observers and reverts the engine to legacy polling, which may cause flickering. This field is optional. |
| isDynamicElement | Boolean | When active, Kameleoon tracks the selector if not immediately found at page load and executes the callback as elements appear. The callback triggers again for each new element matching the selector. This setting supports dynamic menus, infinite scrolling, and pop-ups. This field is optional. |

## runWhenShadowRootElementPresent

The `runWhenShadowRootElementPresent()` method executes the **callback** function when a specific element appears in a shadow DOM set to `mode: open`.

```javascript theme={null}
const wrapper = document.querySelector(".shadow-wrapper");
const shadow = wrapper.attachShadow({ mode: "open" });
const span = document.createElement("span");
span.classList.add("selector-inside-wrapper");
span.textContent = "I'm in the shadow DOM";
shadow.appendChild(span);

Kameleoon.API.Core.runWhenShadowRootElementPresent('.shadow-wrapper', '.selector-inside-wrapper', (elements) => {
    elements[0].innerText = "New text" 
});

```

**Arguments**

| Name | Type | Description |
| - | - | - |
| parentSelector | String | CSS selector for the parent element. This field is mandatory. |
| shadowRootElementSelector | String | CSS selector inside the shadow DOM. This field is mandatory. |
| callback | Function | JavaScript function to execute when the element appears in the shadow DOM. This field is mandatory. |
| isDynamicElement | Boolean | When active, Kameleoon tracks the selector if not immediately found and executes the callback as elements appear. The callback triggers again for each new element matching the selector. This setting supports dynamic menus, infinite scrolling, and pop-ups. |
