> For the complete documentation index, see [llms.txt](https://imtoken.gitbook.io/developers/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://imtoken.gitbook.io/developers/products/webview/sdk.md).

# SDK APIs

## Introduction

With the `@consenlabs-fe/webview`, you can easily access and use the various interfaces built into the imToken WebView environment. Whether you're migrating a DApp to **imToken** or adapting a Web application, you can quickly solve it with minimal code and minimal invasiveness.

The SDK includes functions to obtain the *language environment*, *common native UI*, *route navigation*, *scan QR codes*, etc. The SDK itself does **not contain dependencies** and is only used as a tool to bond the host environment and will not cause any invasive damage to your project.

## Features

### Complete TypeScript support

All interfaces and methods have full type support.

<div align="left"><img src="/files/-MWd2zezzbkwmaqQkf_g" alt=""></div>

### Multi-module support

In modern front-end projects, the `esm` mode is used by default, but we also provide `cjs` `umd` and ways.

### Promise

Based on v1, all our asynchronous interfaces support promise by default.

### Community

We've added support for the community, where you can [create a discussion](https://github.com/consenlabs/webview/discussions/new) for any questions about the API or tools.

## Getting started

If you are looking for a complete project example, please check out the sample applications we have prepared:

* React project sample: [examples/react-app](https://github.com/consenlabs/webview/blob/master/examples/react-app)
* Vue project sample: [examples/vue-app](https://github.com/consenlabs/webview/tree/master/examples/vue-app)
* UMD project sample: [examples/umd](https://github.com/consenlabs/webview/tree/master/examples/umd)

### Install

You can use the package management tool to install `@consenlabs-fe/webview` , this is the recommended way. For this, your project may need the [NodeJS](https://nodejs.org/en/download/) environment with the [NPM](https://www.npmjs.com/) management tool. (or [Yarn](https://yarnpkg.com/))

**NPM:** (recommended installation)

```bash
npm i @consenlabs-fe/webview
```

**Yarn:**

```bash
yarn add @consenlabs-fe/webview
```

**CDN:**

&#x20;`@consenlabs-fe/webview` is available on [unpkg](https://unpkg.com/@consenlabs-fe/webview/dist/index.js) and [jsdelivr](https://cdn.jsdelivr.net/npm/@consenlabs-fe/webview/dist/index.min.js). (the CDN may require some time synchronization, please note the version you are using)

```markup
<script src="https://cdn.jsdelivr.net/npm/@consenlabs-fe/webview/dist/index.min.js" />
```

### Import and usage

Before you can use it, you need to `import` the module:

```typescript
import TokenWebView from '@consenlabs-fe/webview'
```

As a suggestion to maintain compatibility, we recommend that you always check the current environment first:

```typescript
if (TokenWebView.isTokenEnv()) {
  TokenWebView.apis.navigator.setTitle('hello world')
}
```

## API References

All API interfaces, types, and examples are listed here. In fact, if you are using TypeScript, you can already get good type hints in your project.

### General

This is the API that comes with the root module and is usually used to check the environment and the processing of generic scenarios.

#### isTokenEnv

Check if the current context is imToken WebView and return a boolean value.

**Types**

```typescript
type isTokenEnv = () => boolean 
```

**Usage Example**

```typescript
console.log('Currently in imToken: ', TokenWebView.isTokenEnv())
```

####

#### getVersion

Get the current version of the imToken App.

**Types**

```typescript
type getVersion = () => string
```

**Usage Example**

```typescript
console.log('Currently version: ', TokenWebView.getVersion())

// output -> 'Currently version: 2.4.0'
```

####

#### isGreaterThanOrEqualVersion

The current App version is greater than or equal to the specified value.

**Types**

```typescript
type isGreaterThanOrEqualVersion = (version: string) => boolean
```

**Usage Example**

```typescript
const state = TokenWebView.isGreaterThanOrEqualVersion('2.1.0')
console.log('Version greater than or equal to 2.1.0: ', state )

// output -> 'Version greater than or equal to 2.1.0: true'
```

####

#### compareSemver

Compare the two versions of the value and return the number.

Requires that the comparison value must be a [semantic version](https://semver.org/) of the string. The return value rules are the same as for the [JavaScript sort function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort).

**Types**

```typescript
type compareSemver = (versionA: string, versionB: string) => number
```

**Usage Example**

```typescript
const state = TokenWebView.compareSemver('2.1.0', '2.2.0')
console.log(state)

// output -> '0'
```

#### isCancelError

Check if the current error was caused by a user cancellation.

**Types**

```typescript
type isCancelError = (error: Error) => boolean
```

**Usage Example**

```typescript
try {
  // ...
} catch (err) {
  if (TokenWebView.isCancelError(err)) {
    console.log('User cancelled the operation')
  }
}
```

#### ERRORS

Error constants. The source of the error message, most of the time you do not need to compare this constant.

**Types**

```typescript
type ERRORS = Record<string, string>
```

#### apis

API for communicating with the host environment, please see below for details.

### device API

#### getCurrentLanguage

Get the current language environment, which usually comes from the user's settings within the imToken application.

**Types**

```typescript
type getCurrentLanguage = () => Promise<string>
```

**Usage Example**

```typescript
const language = await TokenWebView.apis.device.getCurrentLanguage()
console.log(language)

// output -> 'en-us'
```

#### getCurrentCurrency

Get the current currency,  returns the currency string.

**Types**

```typescript
type getCurrentCurrency = () => Promise<string>
```

**Usage Example**

```typescript
const currency = await TokenWebView.apis.device.getCurrentCurrency()
console.log(currency)

// output -> 'CNY'
```

###

### native API

Provide native platform UI and interaction capabilities.

#### alert

Display the string as an alert box.

**Types**

```typescript
type alert = (content: string) => void
```

**Usage Example**

```typescript
TokenWebView.apis.native.alert('hello world!')
```

####

#### confirm

Display the string as a confirm box.

A user clicks on the confirm or cancel button action will be returned as a Boolean value.

**Types**

```typescript
type confirm = (content: {
  title: string
  message: string
  cancelText: string
  confirmText: string
}) => Promise<boolean>
```

**Usage Example**

```typescript
const isConfirmDeletion = await TokenWebView.apis.native.confirm({
  title: 'Second Confirmation',
  message: 'Remove current connection?',
  confirmText: 'ok',
  cancelText: 'NO',
})
```

#### setLoading

Set the entire WebView to the loading state.

{% hint style="warning" %}
If you do not actively cancel this status, users will not be able to operate. The loaded state will block all interactive events.
{% endhint %}

**Types**

```typescript
type setLoading = (visible: boolean) => void
```

**Usage Example**

```typescript
if (myTaskLoading) {
  TokenWebView.apis.native.setLoading(true)
}
```

#### share

Share a link or picture.

If the shared content is an image, it needs to be pre-converted to `base64` format.

The success of the sharing depends on the user's confirmation and whether the user allows permissions.

**Types**

```typescript
type ShareParamsDefault = {
  title: string
  message: string
  url: string
}

type ShareParamsImage = {
  title: string
  image: string
}

type share = (params: ShareParamsDefault & ShareParamsImage) => Promise<boolean>
```

**Usage Example**

```typescript
const isSuccess = await TokenWebView.apis.native.share({
  title: 'Share',
  message: 'Share this page with others',
  url: location.href,
})
```

#### scanQRCode

Evoke the camera to scan the QR code, if the scan is successful, the parsed string will be returned.

**Types**

```typescript
type scanQRCode = () => Promise<string>
```

**Usage Example**

```typescript
try {
  const text = await TokenWebView.apis.native.scanQRCode()
} catch (err) {
  console.log('scan failed.')
}

```

#### setClipboard

Filling the user's clipboard with strings.

**Types**

```typescript
type setClipboard = (text: string) => void
```

**Usage Example**

```typescript
TokenWebView.apis.native.setClipboard('address')

```

###

### navigator API

Routing navigation and settings page.

#### closeDapp

Close the current DApp.

**Types**

```typescript
type closeDapp = () => void
```

**Usage Example**

```typescript
TokenWebView.apis.navigator.closeDapp()
```

####

#### goBack

Returns the previous level of routing, or closes the app if there is no routing stack.

**Types**

```typescript
type goBack = () => void
```

**Usage Example**

```typescript
TokenWebView.apis.navigator.goBack()
```

####

#### routeTo

Navigate to a specific screen.

**Types**

```typescript
type RouteToParams = {
  screen: string 
  props: {
    title: string
    url: string
  }
}

type routeTo = (params: RouteToParams) => void
```

**Usage Example**

```typescript
// Jump to other DApps

TokenWebView.apis.navigator.routeTo({
  screen: 'DappView',
  props: {
    title: 'DApp API Examples',
    url: 'https://consenlabs.github.io/',
  },
})
```

####

#### getOrientation

Get the direction of the current device.

**Types**

```typescript
type Orientation = 'LANDSCAPE' | 'PORTRAIT'

type getOrientation = () => Promise<Orientation>
```

**Usage Example**

```typescript
const orientation = await TokenWebView.apis.navigator.getOrientation()
console.log(orientation)

// output -> 'LANDSCAPE'
```

####

#### setOrientation

Set the orientation of the current device, which can be very helpful when playing multimedia messages.

**Types**

```typescript
type Orientation = 'LANDSCAPE' | 'PORTRAIT'

type setOrientation = (orientation: Orientation) => void
```

**Usage Example**

```typescript
TokenWebView.apis.navigator.setOrientation('LANDSCAPE')
```

####

#### setTitle

Dynamically set DApp title. No effect to `document.title`.

**Types**

```typescript
type setTitle = (title: string) => void
```

**Usage Example**

```typescript
TokenWebView.apis.navigator.setTitle('MY DAPP')
```

####

### user API

#### showAccountSwitch

Show switchable user wallets. If the switch is successful, the new address will be returned.

**Types**

```typescript
type ChainType =
  | 'ETHEREUM'
  | 'BITCOIN'
  | 'LITECOIN'
  | 'EOS'
  | 'COSMOS'
  | 'TRON'
  | 'BITCOINCASH'
  | 'NERVOS'
  | 'KUSAMA'
  | 'POLKADOT'
  | 'FILECOIN'
  
type showAccountSwitch = (chainType: ChainType | null) => Promise<string>
```

**Usage Example**

```typescript
const address = await TokenWebView.apis.user.showAccountSwitch('ETHEREUM')
console.log(address)

// output -> '0x...'
```

### layout API

#### setOptions

Set the frame layout style of the WebView.&#x20;

This updates the layout of the current WebView synchronously and can only be applied after the page has been loaded and parsed. If you want to **make changes to the layout while the page is loading**, please refer to our preload configuration documentation.

**Types**

```typescript
type HexColor = `#${string}`
type StatusBarStyle = 0 | 1 | 2

type WebViewLayoutOptions = {
  background?: HexColor | Array<HexColor>
  foreground?: HexColor
  isTitleLeft?: boolean
  titleSize?: number
  isTransparent?: boolean
  transparentScrollY?: number
  loadingBackground?: HexColor
  loadingForeground?: HexColor
  bodyBackground?: HexColor
  bodyForeground?: HexColor
  statusBarStyle?: StatusBarStyle
}

type setOptions = (options: WebViewLayoutOptions) => void
```

**Usage Example**

```typescript
TokenWebView.apis.layout.setOptions({
  background: '#000000',
  titleSize: 20,
})
```

####

### internal API

Unstable API, mainly for advanced user custom development and debugging.
