# Client-side APIs

This article presents a set of functions and methods that enable you to extend the personalization capabilities of the user experience on your website.

## Recommendations

The result is returned as a set of products in JSON format.

**Syntax**

<pre class="language-jsx"><code class="lang-jsx"><strong>GF.Recommendations.get(id, opts, callback)
</strong></code></pre>

**Parameters:**

* **id**: The identifier of the recommendations strategy.
* **opts:** Optional parameters
  * **context**: The page context, taken directly from the page unless you explicitly specify another one.
  * **maxProducts**: Overrides the number of products from the Strategy configuration window.
* **callback**: A callback function that is executed once data on recommendations is returned.

**Usage example:**

```jsx
GF.Recommendations.get('6364138cfe9b4f979a044a32', {
	maxProducts: 10
}, function(err, data) {
    if (err) {
        console.log(err);return;
    }
    
	const template = '<a href="{url}" class="demo-recs__item" style="flex:1;margin:0 5px;border: 1px solid #ccc;padding:10px;background: #fff;"><img src="{image_url}" style="display:block;max-width:100px;height:auto;max-height:100px;margin:0 auto;"/><div>{name}</div><div>{price}</div></a>';
	let html = '<div class="demo-recs" style="display:flex;">';
	for(let i = 0; i < data.slots.length; i++) {
		html += template.replace(/{([^{}]+)}/g, function(keyExpr, key) {
			return data.slots[i].item[key] || "";
		});
	}
	html += '</div>';
	document.body.insertAdjacentHTML('afterbegin', html);
})
```

## Wait for a CSS Element

This method waits for the loading of an element on the page and then executes a function.

**Syntax**

```jsx
GF.waitForElement(selector, callback, minElements, interval, maximumRetries)
```

**Parameters:**

* **selector:** A valid CSS selector that specifies which element to look for in the DOM.
* **callback:** The function to execute.
* **minElements (optional, default: 1):** The minimum number of selected resources that must be rendered before executing the function.
* **interval (optional, default: 100):** How often the page should recheck for the element (in milliseconds).
* **maximumRetries (optional, default: infinite):** The maximum number of page recheck attempts to find the elements.

**Returns: Nothing**

**Activation Example:**

```jsx
GF.waitForElement(".area-link",console.log ('test'), 1, 100, 5)
```

## Wait for an event

This method waits for a specific event to occur on the page and then executes a function.

**Syntax:**

```jsx
GF.PubSub.on('<condition>', callback: <function>)
```

The function is triggered when the event or page view is registered by the browser.

**Available conditions:**

* **sl-event**: Trigger for event occurrence.
* **spa**: Trigger for SPA event occurrence.

**Usage example and response:**

```jsx
GF.PubSub.on('sl-event', function (data) {
  console.log(data)
});

// Example response:
{
    "event": {
        "name": "Add to Cart",
        "props": {
            "eventType": "add-to-cart-v1",
            "value": 8.51,
            "currency": "BYN",
            "productId": "2.274366",
            "quantity": 1,
            "cart": [
                {
                    "productId": "2.274366",
                    "quantity": 1,
                    "itemPrice": 8.51
                }
            ]
        }
    },
    "eventName": "Add to Cart",
    "properties": {
        "eventType": "add-to-cart-v1",
        "value": 8.51,
        "currency": "BYN",
        "productId": "2.274366",
        "quantity": 1,
        "cart": [
            {
                "productId": "2.274366",
                "quantity": 1,
                "itemPrice": 8.51
            }
        ]
    }
}
```

## Overlay

**Syntax:**

```jsx
const overlay = new GF.Overlay(
    { htmlCode: <string>, cssCode: <string>, jsCode: <string> },
    { destroyOnClose: <boolean>, closeIcon: <string>, closeEventName: <string> })
overlay.open();
```

**Parameters:**

* **Layout** (htmlCode, cssCode, jsCode): Basic parameters for the overlay.
* **Optional parameters**
  * **destroyOnClose**: Removes the overlay from the DOM when closed. Default is true.
  * **closeIcon**: Customized overlay close icon (string value, e.g., inline SVG).
  * **closeEventName**: Trigger an event when the overlay is closed.

**Usage example:**

```jsx
const overlay = new GF.Overlay({ htmlCode: '<div class="test">123</div>', cssCode: '.test{background:#fff;padding:20px;}'})
overlay.open();
```

## Social Proof and Product Data

**Parameters:**

* **SKU Array**
* **Options**
  * **interest**: Boolean value, returns the type of interest in the product (purchase, view).
  * **timeframes (daily, twoDays, weekly, twoWeeks, monthly) -** an array of string values, returns the number of interest events relative to the product (purchases, views).
  * **data**: Boolean value, specifies whether to return product properties from the feed.

**Usage example:**

```jsx
GF.ServerUtils.getProductsData(['303665', '304825'], {
  interest: true,
  timeframes: ['weekly'],
  data: true,
}).then((data) => console.log(data));
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://developer.gravityfield.ai/lang/en/implementation/client-side-apis.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
