# Widget Plus Window API

The Widget Plus Window API exposes public functions that can be called to setup or make configuration changes to the widgets on the page.

## Functions

### initAllWidgets

Initializes all widgets on the current page.

#### Example Usage

```jsx
window.okeWidgetApi.initAllWidgets();
```

### initWidget

Initializes or reinitializes a particular widget.

#### Example Usage

```jsx
const widgetElement = document.querySelector('[data-oke-widget]');
window.okeWidgetApi.initWidget(widgetElement);
```

#### Parameters

<table><thead><tr><th width="262">Parameter</th><th width="215">Description</th><th width="166">Value Type</th><th width="114">Supported Values</th><th width="102" align="center">Required</th></tr></thead><tbody><tr><td><code>widgetElement</code></td><td>The widget <code>HTMLElement</code> which will be initialized.</td><td><code>HTMLElement</code></td><td></td><td align="center"><span data-gb-custom-inline data-tag="emoji" data-code="2705">✅</span></td></tr><tr><td><code>forceReinitialization</code></td><td>Determines whether or not to force the widget to reinitialize if it has already been initialized.</td><td><code>boolean</code></td><td><code>true</code>, <code>false</code></td><td align="center"></td></tr></tbody></table>

### setProduct

Sets a widget to 'product' mode and to only show review data for the specified product.

#### Example Usage

```jsx
const widgetElement = document.querySelector('[data-oke-widget]');
window.okeWidgetApi.setProduct(widgetElement, 'shopify-7551554945263');
```

#### Parameters

| Parameter       | Description                                                                         | Value Type    | Supported Values                                                                  |       Required       |
| --------------- | ----------------------------------------------------------------------------------- | ------------- | --------------------------------------------------------------------------------- | :------------------: |
| `widgetElement` | The widget `HTMLElement` which will be set with a particular product’s data.        | `HTMLElement` |                                                                                   | :white\_check\_mark: |
| `productId`     | Sets the widget in 'product' mode with only reviews data for the specified product. | `string`      | Any valid Product ID in the format `shopify-{product_id}` e.g. `shopify-1234567`. | :white\_check\_mark: |

### setGroup

Sets a widget to 'group' mode and to only show review data for the specified group.

#### Example Usage

```jsx
const widgetElement = document.querySelector('[data-oke-widget]');
window.okeWidgetApi.setGroup(widgetElement, 'd06b2294-7f17-48fe-9fd6-155e8cb07a54');
```

#### Parameters

| Parameter       | Description                                                                             | Value Type    | Supported Values                                                            |       Required       |
| --------------- | --------------------------------------------------------------------------------------- | ------------- | --------------------------------------------------------------------------- | :------------------: |
| `widgetElement` | The widget/target `HTMLElement` which will be set with a particular product’s data.     | `HTMLElement` |                                                                             | :white\_check\_mark: |
| `groupId`       | Sets the widget in 'group' mode with only reviews data for the specified product group. | `string`      | Any valid Group ID. [Where can I find a Group ID?](#how-to-find-a-group-id) | :white\_check\_mark: |

#### How to Find a Group ID <a href="#how-to-find-a-group-id" id="how-to-find-a-group-id"></a>

1. Open **Okendo Admin.**
2. Navigate to **Groups** (Reviews > Groups).
3. Select the Group you would like to use for your widget.
4. Look in the URL for the group page and you will see a [GUID](https://www.techtarget.com/searchwindowsserver/definition/GUID-global-unique-identifier) at the end of the URL. This is the Group ID.

<figure><img src="/files/9sj5LtU6YD5sPg8gdpgK" alt=""><figcaption><p>Group ID is located in the browser address bar at the end of the URL.</p></figcaption></figure>

### setWidgetLocale

Sets the widget locale and/or locale variant for the widgets to use for translation purposes.

#### Example Usage

```jsx
window.okeWidgetApi.setWidgetLocale('fr');
```

#### Parameters

<table><thead><tr><th width="129">Parameter</th><th>Description</th><th width="127">Value Type</th><th>Supported Values</th><th align="center">Required</th></tr></thead><tbody><tr><td><code>locale</code></td><td>The locale code for the language you want the set the widgets to use.</td><td><code>string</code></td><td><code>da</code> | <code>de</code> | <code>el</code> | <code>en</code> | <code>es</code> | <code>fr</code> | <code>id</code> | <code>it</code> | <code>ja</code> | <code>ko</code> | <code>nl</code> | <code>no</code> | <code>pl</code> | <code>pt</code> | <code>ru</code> | <code>sv</code> | <code>th</code> | <code>vi</code> | <code>zh-TW</code></td><td align="center"><span data-gb-custom-inline data-tag="emoji" data-code="2705">✅</span></td></tr><tr><td><code>variant</code></td><td>The variant code for the language you want to set the widget to use.<br><br>Currently only support formal/informal for the German locale <code>de</code><br></td><td><code>string</code></td><td><code>formal</code> | <code>informal</code></td><td align="center"></td></tr></tbody></table>

## Custom Initialization

If our standard widget initialization pattern doesn't work correctly for your application, you may need to manually re-initialize the widget(s).

### Manually Initialize a Widget

A common practice is to initialize the widget via the Window API by placing a `script` block or file at the base of your HTML document.\
\
You are then able to watch the `document.readyState` lifecycle and initialise widgets using the `window.okeWidgetApi`.

```javascript
<script type="text/javascript">
((document, window) => {  
    const reviewsWidgetHolder = document.querySelector('[data-oke-widget]');
    if (reviewsWidgetHolder) {
        const handleDocumentLoaded = function (e) {
            if (window.okeWidgetApi) {
                window.okeWidgetApi.initWidget(reviewsWidgetHolder, true);
            }
        }
    
        if (document.readyState !== 'interactive' && document.readyState !== 'complete') {
            document.addEventListener('readystatechange', () => {
                handleDocumentLoaded();
            }, { once: true });
        }
        else {
            handleDocumentLoaded();
        }
    }
})(document, window);
</script>
```

### Overriding The Product Details URL - Stores With Shopify Markets / Custom Domains / Headless

We give merchants the ability to override the way their product detail URLs are generated by the Reviews Widget.

A common use-case for this functionality would be in the event a store is using Shopify Markets, Custom Domains, a Headless implementation.

In your theme or a custom html/liquid block you can supply a product URL formatter function on the `window` object which the reviews widget will use when generating links to products.

**It is recommended to place this snippet in the \<head> of your site above the {{ content\_for\_header }}**:

**Example Markets Usage When Using Shopify Translate and Adapt Style Sub-Folders for \<market>-\<locale> e.g. <https://www.store-domain.com/ja-ja/>**

```
<script type="text/javascript">
window.okeProductUrlFormatter = (product) => {
    if (product && window?.Shopify?.routes?.root?.length && window?.Shopify?.routes?.root !== '/') {
        return window.Shopify.routes.root + 'products/' + product.productHandle + '/?id=' + product.productId + (product.variantId ? ('&variantId=' + product.variantId) : '');
    }
};
</script>
```

**Example Markets Usage**

```
<script type="text/javascript">
  window.okeProductUrlFormatter = (product) => {
    // Retrieve current Shopify locale
    const locale = window.Shopify.locale || 'en';

    // Base URL for each locale
    // You could use window.Shopify.routes.root
    let baseUrl;

    // Switch statement to handle different locales
    switch (locale) {
      case 'en': // Default English market
        baseUrl = 'https://www.my-store.com';
        break;
      case 'ja': // Japanese market
        baseUrl = 'https://www.my-store.co.jp';
        break;
      case 'au': // Australian market
        baseUrl = 'https://www.my-store.com.au';
        break;
      case 'zh': // Chinese market
        baseUrl = 'https://www.my-store.cn';
        break;
      case 'de': // German market
        baseUrl = 'https://www.my-store.de';
        break;
      // Add more cases for other locales as needed
      default: // Fallback for unsupported locales
        baseUrl = 'https://www.my-store.com';
        break;
    }

    // Construct the product URL
    const productUrl = `${baseUrl}/products/${product.productHandle}/?id=${product.productId}`;

    // Include variantId if available
    if (product.variantId) {
      return `${productUrl}&variantId=${product.variantId}`;
    }

    return productUrl;
  };
</script>

```

#### Parameters

<table><thead><tr><th width="129">Parameter</th><th>Description</th><th width="127">Value Type</th><th>Object Values</th><th align="center">Required</th></tr></thead><tbody><tr><td><code>product</code></td><td>This is a Javascript object which is passed to your function to provide product information you may use when constructing a product details URL.</td><td><code>object</code></td><td><code>{ productHandle: string;</code><br><code>productId: string;</code><br><code>variantId: string }</code></td><td align="center"><span data-gb-custom-inline data-tag="emoji" data-code="2705">✅</span></td></tr></tbody></table>

## Events

For merchants not using Google Analytics, an `oke-analytics-event` is raised in conjunction with any of our standard Google Analytics interaction and view events.\
\
You can subscribe to the event and forward it on to other analytics providers like so:

```
document.addEventListener('oke-analytics-event', (event) => {
  // event.detail contains analytics information properties
  console.log(JSON.stringify(event.detail));
});
```

#### event.detail Properties

| Property         | Description                                                                                                                                                                                  |                                                                                                                                                                                                                                                                                                                                                                  |   |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | - |
| `event`          | The name of the event in snake case                                                                                                                                                          |                                                                                                                                                                                                                                                                                                                                                                  |   |
| `event_category` | `'Okendo'`                                                                                                                                                                                   |                                                                                                                                                                                                                                                                                                                                                                  |   |
| `event_label`    | A custom label based on the event or falls back to the product name if not supplied                                                                                                          |                                                                                                                                                                                                                                                                                                                                                                  |   |
| `event_type`     | <p><code>'interaction'</code>                                                                                                                                                                | <code>'view'</code><br><br><code>interaction</code> : When a user directly interacted with the widget<br><br><code>view</code> : When widget based time tracking is enabled (see: <a href="https://support.okendo.io/en/articles/6787536-tracking-widget-on-screen-time"><https://support.okendo.io/en/articles/6787536-tracking-widget-on-screen-time></a>)</p> |   |
| `okendo_product` | `'reviews'`                                                                                                                                                                                  |                                                                                                                                                                                                                                                                                                                                                                  |   |
| `product_label`  | <p>The product name/label if the reviews widget is displaying a specific product.<br><br>This will be empty when the widget displays "All Reviews", "Grouped" , or "Collection" reviews.</p> |                                                                                                                                                                                                                                                                                                                                                                  |   |


---

# 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://docs.okendo.io/on-site/storefront-javascript-api/widget-plus-window-api.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.
