npm package: @skolon/widget-sdk
Description: An SDK for creating widgets in Skolon, providing an API to interact with Skolon through a widget.
Latest version: 0.3.0

# Skolon Widget SDK

An SDK for creating widgets in Skolon, providing an API to interact with Skolon through a widget.

Widgets are small and simple web apps for users to quickly view and interact with, available
right in their app collection.

They can be used to show users up to date information from your platform, or give them easy access
to common actions.

## Table of contents

1.  [Installation](#installation)
2.  [Example Usage](#example-usage)
3.  [Sandboxing](#sandboxing)
4.  [API](#api)

## Installation

```bash
yarn add @skolon/widget-sdk
```

or

```bash
npm install @skolon/widget-sdk
```

## Example Usage

### Widget

```javascript
import {
  init,
  loadSettings,
  saveSettings,
  openModal,
  registerSettingsCallback,
  registerCustomMenuItems,
} from "@skolon/widget-sdk";

let state = { language: "en-gb", useMetric: true };

init()
  .then(({ preferredLanguage }) => {
    state.language = preferredLanguage;
    return loadSettings();
  })
  .then((settingsString) => {
    if (settingsString) {
      const settings = JSON.parse(settingsString);
      state = { ...settings, language: state.language };
    }

    registerSettingsCallback(() => {
      openModal(
        `https://my-site/widget/settings?useMetric=${state.useMetric}`
      ).then((response) => {
        if (response.closedBy === "Modal" && response.responseData) {
          const { useMetric } = JSON.parse(response.responseData);

          state.useMetric = useMetric;
          saveSettings(JSON.stringify(state));
        }
      });
    });

    registerCustomMenuItems([
      {
        callback: () => console.log("Do something cool! :)"),
        label: "Cool button",
      },
      {
        callback: () => openModal("http://example.com"),
        label: "Open example.com",
      },
    ]);
  });
```

### Modal

```javascript
import { init, closeModal } from "@skolon/widget-sdk";

let state = { language: "en-gb", useMetric: true };

init().then(({ preferredLanguage }) => {
  state.language = preferredLanguage;

  const queryParams = new URLSearchParams(location.search);
  // Initialize the preselected value to the user's current setting
  state.useMetric = queryParams.get("useMetric");

  // Close the modal and notify the widget of the updated useMetric setting when
  // the user submits the form
  document.querySelector("form").addEventListener("submit", (event) => {
    event.preventDefault();

    closeModal(JSON.stringify({ useMetric: state.useMetric }));
  });

  document.querySelector("#cancel-button").addEventListener("click", () => {
    // Close the modal without sending any updated settings if the user clicks
    // cancel
    closeModal();
  });
});
```

## Guide

A guide for writing an example widget can be found [here](https://skolon.com/wp-content/uploads/2022/12/Development-guide-for-Widgets-in-Skolon.pdf)

## Sandboxing

The widgets are loaded in a sandboxed iframe, which results in some restrictions in what can be done. This is done using the [iframe sandbox attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox).

The only permissions given are `allow-scripts` and `allow-same-origin`. For a full list of permissions not given, see [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox).

Some of the things blocked by the sandbox can instead be done using this SDK, such as opening links using `openTab`.

## Getting data about the user

Getting authorized data about the user can be done through Skolon's APIs, the same way it is done
for integrations of regular edtech apps.

## API

<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

#### Table of Contents

- [init](#init)
- [registerSettingsCallback](#registersettingscallback)
  - [Parameters](#parameters)
- [openTab](#opentab)
  - [Parameters](#parameters-1)
- [saveSettings](#savesettings)
  - [Parameters](#parameters-2)
- [loadSettings](#loadsettings)
- [openModal](#openmodal)
  - [Parameters](#parameters-3)
- [closeModal](#closemodal)
  - [Parameters](#parameters-4)
- [externalLogin](#externallogin)
  - [Parameters](#parameters-5)
- [notifyExternalLoginSuccess](#notifyexternalloginsuccess)
  - [Parameters](#parameters-6)
- [notifyExternalLoginFailure](#notifyexternalloginfailure)
  - [Parameters](#parameters-7)
- [getAuthCode](#getauthcode)
  - [Parameters](#parameters-8)
- [WidgetSize](#widgetsize)
  - [Properties](#properties)
- [InitData](#initdata)
  - [Properties](#properties-1)
- [ModalResponse](#modalresponse)
  - [Properties](#properties-2)
- [ExternalLoginResponse](#externalloginresponse)
  - [Properties](#properties-3)
- [OpenModalOptions](#openmodaloptions)
  - [Properties](#properties-4)

### init

Initiates the library. This should always be the first method called when used in a widget or modal.

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[InitData](#initdata)>**&#x20;

### registerSettingsCallback

Tells Skolon to render a settings button for the widget. The provided
callback will be called when the user clicks the button.

#### Parameters

- `callback` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)**&#x20;

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)**&#x20;

### openTab

Opens an url in a new tab in the user's browser. This should only be done on
user interaction, as it may otherwise be blocked.

#### Parameters

- `url` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** The URL of the tab to open

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)**&#x20;

### saveSettings

Saves user specific settings. The saved data will be available for widgets and modals for the user on all devices.

#### Parameters

- `settings` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** A string representing the settings to save, for example serialized JSON. 16383 characters or shorter.

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)**&#x20;

### loadSettings

Loads previously saved settings.

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?>**&#x20;

### openModal

Opens a modal displaying an iframe with the specified URL. Only callable from the main widget.

#### Parameters

- `url` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** The url to render in the modal.
- `options` **[OpenModalOptions](#openmodaloptions)?** Options for how the modal should be rendered. (optional, default `{}`)

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[ModalResponse](#modalresponse)>** A promise that resolves once the modal is closed.

### closeModal

Closes the modal and optionally send data to the widget. Only callable from a modal.

#### Parameters

- `data` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?** A string representing the settings to save, for example serialized JSON. (optional, default `null`)

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)**&#x20;

### externalLogin

Initiates a login flow to a non-Skolon service in a new tab. The final callback URL should call either [notifyExternalLoginSuccess](#notifyexternalloginsuccess) or [notifyExternalLoginFailure](#notifyexternalloginfailure). Only callable from the main widget.

#### Parameters

- `url` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** The URL that initiates the login flow

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[ExternalLoginResponse](#externalloginresponse)>** A promise that resolves once either [notifyExternalLoginSuccess](#notifyexternalloginsuccess) or [notifyExternalLoginFailure](#notifyexternalloginfailure) is called by a page in the login flow.

### notifyExternalLoginSuccess

Notifies the widget that the login was successful

#### Parameters

- `data` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?** A string representing the settings to save, for example serialized JSON. (optional, default `null`)

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)**&#x20;

### notifyExternalLoginFailure

Notifies the widget that the login failed

#### Parameters

- `data` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?** A string representing the settings to save, for example serialized JSON. (optional, default `null`)

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)**&#x20;

### getAuthCode

Gets an OAuth authorization code that can be exchanged for an access token for Skolon's API.

This is a preview feature, and may be subject to change.

#### Parameters

- `clientId` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** The client ID of your application
- `scopes` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>?** A list of scopes to request (optional, default `[]`)

Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>** A promise resolving to an OAuth authorization code. This promise will
reject if the user doesn't approve the requested scopes

### WidgetSize

Type: [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)

#### Properties

- `width` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** The number of slots in the grid that the width of the widget covers. Either 1 or 2.
- `height` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** The number of slots in the grid that the height of the widget covers. Either 1 or 2.

### InitData

Type: [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)

#### Properties

- `widgetSize` **[WidgetSize](#widgetsize)**&#x20;
- `preferredLanguage` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** The user's preferred language. An ISO 639-1 language code optionally followed by a ISO 3166-1 alpha-2 country code. E.g. 'sv' or 'en-gb'.

### ModalResponse

Type: [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)

#### Properties

- `closedBy` **(`"Skolon"` | `"Modal"`)**&#x20;
- `data` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?** The data provided in the call to [closeModal](#closemodal). Will always be null if closed by Skolon

### ExternalLoginResponse

Type: [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)

#### Properties

- `success` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** True if [notifyExternalLoginSuccess](#notifyexternalloginsuccess) was called, false if [notifyExternalLoginFailure](#notifyexternalloginfailure) was called.
- `data` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?** The data passed to [notifyExternalLoginSuccess](#notifyexternalloginsuccess) or [notifyExternalLoginFailure](#notifyexternalloginfailure), if any.

### OpenModalOptions

Type: [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)

#### Properties

- `size` **(`"small"` | `"medium"` | `"large"`)?** Size of the modal.