npm package: @govflanders/vl-widget-global-header-types
Description: TypeScript definitions for GlobalHeaderClient
Author: Maarten Van Steenkiste
Latest version: 2.0.27

## Introduction

This guide is for developers looking to integrate the Flanders Global Header into their websites.

## Adding a Flanders Global Header to Your Website

You can integrate the **Flanders Global Header** into your website using one of two methods: the **entry script** or the **embed script**. Each serves a different purpose.

💡 Note: the embed url differs from the previous one. Now it's `api/v2` instead of `api/v1`.

### Using the Embed Script (Automatic Mounting)

Use the embed script for quick and automatic integration with minimal setup. The embed script is meant to be placed directly inside the DOM where you want the header to appear. It automatically renders the header at the script's location in the HTML.

Example of using the embed script:

```html
<!doctype html>
<html lang="nl">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Global header embed script example</title>
  </head>
  <body>
    <!-- For the UUID, you should use your widget-id -->
    <!-- If you want to use the TNI environment, use https://widgets.tni-vlaanderen.be instead -->
    <script src="https://widgets.vlaanderen.be/api/v2/widget/9717ae3b-84e8-43b2-a814-e35a2547927f/embed"></script>
    <div class="your-website-code">👋 Hello world</div>
  </body>
</html>
```

⚠️ Warning: the `window.globalHeaderClient` object will only be available after the script is resolved. If it's necessary to have direct access to the `window.globalHeaderClient`, use the entry script or listen for the `widget.global_header.mounted` event.

**💡 Tip:** The widget dispatches a `widget.global_header.mounted` event when it's ready. You can listen for this event to know when the widget is mounted and ready for interaction:

```javascript
window.addEventListener('widget.global_header.mounted', async () => {
  // Widget is now mounted and ready
  const config = await window.globalHeaderClient.getConfig();
  console.log('Global Header Widget mounted', config);
});
```

## Widget Events

The widget dispatches the following events that you can listen for:

| Event                                 | Description                                                |
| ------------------------------------- | ---------------------------------------------------------- |
| `widget.global_header.mounted`        | Fired when the widget is mounted and ready for interaction |
| `widget.global_header.contact.opened` | Fired when the contact menu is opened                      |
| `widget.global_header.contact.closed` | Fired when the contact menu is closed                      |

Example usage:

```javascript
window.addEventListener('widget.global_header.contact.opened', () => {
  console.log('Contact menu opened');
});

window.addEventListener('widget.global_header.contact.closed', () => {
  console.log('Contact menu closed');
});
```

### Using the Entry Script (Manual Mounting)

Use the entry script if you need more control over when, where and how the header is mounted. The entry script should be placed in the `<head>` section of your HTML, preferably at the top. This is essential because the `window.globalHeaderClient` object is only available after this script has loaded. With the entry script, the header does not render automatically, so you'll need to call the `mount` method to display it.

Example of using the entry script:

```html
<!doctype html>
<html lang="nl">
  <head>
    <!-- For the UUID, you should use your widget-id -->
    <!-- If you want to use the TNI environment, use https://widgets.tni-vlaanderen.be instead -->
    <script src="https://widgets.vlaanderen.be/api/v2/widget/9717ae3b-84e8-43b2-a814-e35a2547927f/entry"></script>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Global header entry script example</title>
  </head>
  <body>
    <div class="your-website-code">👋 Hello world</div>
    <script>
      window.globalHeaderClient.mount(); // Mount the header manually after the script has loaded
    </script>
  </body>
</html>
```

### Summary

- **Entry script**: Use in the `<head>`, requires manual mounting with `window.globalHeaderClient.mount()` method.
- **Embed script**: Place directly in the DOM, automatically renders the header at the script's location.

## Using the `window.globalHeaderClient` API

The widget is available on the global window object as `window.globalHeaderClient`. You can import the types from global-header-types to use them in your project, if you're using typescript (more info [here](#typescript-support)).

Example of using the `window.globalHeaderClient` object in javascript:

```javascript
const client = window.globalHeaderClient;

const contactLink = {
  label: 'Contact',
  href: '/contact',
};

const feedbackLink = {
  label: 'Feedback',
  href: 'https://example.com/feedback',
  isExternal: true,
  target: '_blank',
};

client.accessMenu.setMainLinks([contactLink, feedbackLink]);
```

Checkout the [GlobalHeaderClient](./interfaces/GlobalHeaderClient.html) here to see all the available methods.

## Migration guide: Upgrading from v4 to v5

If you’re currently using version 4 of the Global Header Widget, please follow this guide to upgrade to version 5. This guide highlights the key changes and steps you need to take to ensure a smooth transition.

### Remove client library script links

No more client library or polyfill scripts: In version 5, you no longer need to include any additional client library or polyfill script links in your HTML. Access to the `window.globalHeaderClient` object is automatically provided when you include either the entry script or the embed script (after the script is loaded).
Action Required:

- Remove any `<script>` tags that reference client libraries or polyfill libraries for the widget.
- Ensure that either the entry script or the embed script is included in your HTML.

### Eliminate installable packages

Script-based integration only: Version 5 removes the need for installable packages via npm or yarn. All functionalities are now accessible by including script tags directly in your HTML’s `<head>` or `<body>` section.

Action Required:

- Uninstall any npm or yarn packages related to the widget
- Delete any import or require statements in your JavaScript code that reference the widget.

### Update Embed script links

Version Update in Embed Links: If you’re using the embed script method to include the widget, you need to update the version number in your script’s src URL from 'v1' to 'v2'. [Example here](#adding-a-flanders-global-header-to-your-website).

### Update API usage

API Changes: The `window.globalHeaderClient` API has been updated in version 5. Methods, their signatures, and usage patterns may have changed. Refer to the [GlobalHeaderClient](./interfaces/GlobalHeaderClient.html) section for detailed information on the new methods and their parameters.

Action Required:

- Review all instances where you interact with `window.globalHeaderClient`.
- Update your code to align with the new [GlobalHeaderClient](./interfaces/GlobalHeaderClient.html) methods and their signatures.
- Pay special attention to asynchronous methods that now return promises.

Example:

```diff
// Using widgets V4
- vl.widget.client.capture(
-   // Verplichte capture functie.
-   function(widget) {
-     if (widget.getPluginTypeId() === 'global_header') {
-       widget.getExtension('contact', 'unsafe').resetServicePoints();
-     }
-   },
- );
// Using widgets V5
+ globalHeaderClient.contact.resetServicePoints();
```

#### Changes in Session Management

In version 5, the header no longer maintains a separate session state. This change entails:

- Elimination of inactivity checks
- Removal of background calls for additional session data
- Absence of a separate `sessionStorage`

This streamlining simplifies the session management process and reduces session-related errors.

#### Changes in the Profile Method

In version 5 of the Global Header Widget, there are significant updates to the profile management functionality:

- The `configure` method has been replaced by the `setProfile` method in the `accessMenu`.
- The `loginRedirectUrl` parameter is now deprecated.
- A new `idpData` object has been introduced, allowing you to pass additional user information, such as the user's name, if they are signed in.

**Example of Profile Method Usage:**

```diff
// Using widgets V4
- vl.widget.client.capture(
-   // Required capture function.
-   function(widget) {
-     if (widget.getPluginTypeId() === 'global_header') {
-       widget.getExtension('citizen_profile.session', 'unsafe').configure({ active: true });
-     }
-   },
- );
// Using widgets V5
+ globalHeaderClient.accessMenu.setProfile({ active: true });
```

**Key Points:**

- Ensure to replace any instances of the `configure` method with `setProfile` in your codebase.
- Review your implementation for any dependencies on the deprecated `loginRedirectUrl`.
- Optional: Utilize the new `idpData` object to enhance user profile management by including relevant user details.

### Accessing `window.globalHeaderClient`

Unified Access via Scripts: In version 5, you can access the `window.globalHeaderClient` object regardless of whether you use the entry script or the embed script.

Action Required:

- Ensure that you include either the entry script or the embed script in your HTML.

### Verify Styling and Rendering

After integrating version 5 of the widget into your website, it’s important to thoroughly review its appearance and functionality to ensure everything works as expected. Some styling adjustments might be necessary due to changes in the widget’s design or your site’s CSS.

Action Required:

- Test Across Browsers: Check the widget in all supported browsers to confirm consistent styling and behavior.
- Inspect for Conflicts: Look for any CSS conflicts between the widget and your site’s stylesheets.
- Adjust Styles if Needed: Modify your CSS or override styles to resolve any layout or design issues.
- Seek Assistance: If problems persist, don’t hesitate to [contact us](#contact-information) for support.

## Language Switching

The **Global Header Widget** v5 now supports multiple languages. The widget automatically adapts to the language of the document. It observes the `lang` attribute on the `<html>` tag, so it's the implementer's responsibility to handle any language switching functionality. If the `lang` attribute changes, the widget will update to display the correct language.

Supported languages:

- nl (Dutch)
- fr (French)
- de (German)
- en (English)

To change the document language, you can use the following JavaScript snippet:

```js
window.document.documentElement.lang = 'nl'; // 'nl', 'en', 'de' or 'fr'
```

This will switch the document's language to Dutch, and the widget will automatically reflect the change.

Notes:

- When using a multilingual widget, ensure its configuration also supports multiple languages.
- Lang tag variants are also handled correctly (for example, like `NL` or `nl-BE`)
- Take a look at the documentation for multilingual objects [here](./types/Translatable.html).

## Browser Support

The **Global Header Widget** supports the two most recent versions of all major browsers:

- Google Chrome
- Mozilla Firefox
- Microsoft Edge
- Safari

Please ensure your users are on the latest versions of these browsers to guarantee full functionality of the widget.

## Typescript Support

The **`@govflanders/vl-widget-global-header-types`** package provides TypeScript types and interfaces for interacting with the **Global Header Widget**. This widget is embedded in customer web pages and exposes a client object (`window.globalHeaderClient`) that allows for dynamic configuration and interaction with the global header.

By using the types defined in this package, developers can ensure type-safe interactions with the widget while improving their development experience (DX) by utilizing autocompletion and built-in documentation.

### Installation

To install the `global-header-types` package, use the following command:

```bash
npm install -D @govflanders/vl-widget-global-header-types
```

or

```bash
yarn add -D @govflanders/vl-widget-global-header-types
```

**Note:** It’s recommended to use the caret (^) symbol in your package.json to stay updated with the latest minor and patch versions.

### Usage example

Example of using the types to interact with the widget:

```typescript
import { GlobalHeaderClient, MainLink } from '@govflanders/vl-widget-global-header-types';

const client: GlobalHeaderClient = window.globalHeaderClient;

const contactLink: MainLink = {
  label: 'Contact',
  href: '/contact',
};

const feedbackLink: MainLink = {
  label: 'Feedback',
  href: 'https://example.com/feedback',
  isExternal: true,
  target: '_blank',
};

client.accessMenu.setMainLinks([contactLink, feedbackLink]);
```

## Content Security Policy (CSP)

To ensure the secure integration of the **Global Header Widget**, you need to configure your Content Security Policy (CSP) with the following directives:

### Production Environment CSP Configuration

The minimum required CSP directives for using the global-header in a production environment are:

| Directive     | Value                                      |
| ------------- | ------------------------------------------ |
| `connect-src` | `https://widgets.vlaanderen.be`            |
| `connect-src` | `wss://chat.contactcenter.vlaanderen.be`   |
| `connect-src` | `https://chat.contactcenter.vlaanderen.be` |
| `connect-src` | `https://contactapi.vlaanderen.be`         |
| `font-src`    | `https://ui.vlaanderen.be`                 |
| `font-src`    | `https://assets.vlaanderen.be`             |
| `font-src`    | `https://widgets.vlaanderen.be`            |
| `img-src`     | `data:`                                    |
| `img-src`     | `https://assets.vlaanderen.be`             |
| `img-src`     | `https://widgets.vlaanderen.be`            |
| `script-src`  | `https://widgets.vlaanderen.be`            |

### TNI Environment CSP Configuration

The minimum required CSP directives for using the global-header in a TNI environment are:

| Directive     | Value                                          |
| ------------- | ---------------------------------------------- |
| `connect-src` | `https://widgets.tni-vlaanderen.be`            |
| `connect-src` | `wss://tni.contactapi.uat-vlaanderen.be`       |
| `connect-src` | `https://chat.contactcenter.dev-vlaanderen.be` |
| `connect-src` | `https://tni.contactapi.uat-vlaanderen.be`     |
| `font-src`    | `https://ui.vlaanderen.be`                     |
| `font-src`    | `https://assets.vlaanderen.be`                 |
| `font-src`    | `https://widgets.tni-vlaanderen.be`            |
| `img-src`     | `data:`                                        |
| `img-src`     | `https://assets.vlaanderen.be`                 |
| `img-src`     | `https://widgets.tni-vlaanderen.be`            |
| `script-src`  | `https://widgets.tni-vlaanderen.be`            |

### Additional CSP for Screensharing

If you're using the screensharing extension in the contact menu, include the following additional directives:

| Directive     | Value (Production & TNI) |
| ------------- | ------------------------ |
| `connect-src` | `cobrowse.io`            |
| `connect-src` | `*.cobrowse.io`          |
| `connect-src` | `wss://*.cobrowse.io`    |

### Further Information

For more detailed information about the cobrowse CSP settings, please refer to the [Cobrowse SDK Installation Guide](https://docs.cobrowse.io/sdk-installation/web#content-security-policies-csps).

Ensure that your CSP settings are correctly configured to avoid any issues with the widget's functionality and security. If you have any questions or need further assistance, please refer to the [Contact Information](#contact-information) section.

## Contact Information

If you need assistance or have any questions regarding the **Global Header Widget**, feel free to reach out to us:

- **Support Portal**: [Widget platform](https://vlaamseoverheid.atlassian.net/wiki/spaces/IKPubliek/pages/2339897467/Widget-platform)

Our team is here to help with any issues or inquiries you might have.

## Search Keywords

- Global Header Integration
- Flanders Widget Setup
- Flanders Global Header
- V5 Widget Migration
- GlobalHeaderClient API
- Embed Script Example
- Entry Script Mounting
- Multilingual Global Header
- Language Switching in Widgets
- Widget Browser Support
- Global Header JavaScript API
- Dynamic Header Links
- TypeScript Widget Integration
- Flanders Widget API Usage
- V4 to V5 Migration Guide