# SDK APIs

## 介绍

借助于 `@consenlabs-fe/webview`，我们可以轻松地访问和使用 imToken WebView 环境中的各种接口。无论是将 DApp 迁移到 imToken 应用还是改编自己的 Web 应用程序，都可以用最少的代码和最小的侵入性快速解决。

该 SDK 包括获得语言环境、Native UI、路由导航、扫描二维码等功能。SDK 本身不包含依赖性，只作为绑定宿主环境的工具，不会对你的项目造成任何侵入性的损害。

## 支持功能

### 完善的 TypeScript 支持

所有的接口都有完善的类型支持，大部分场景下甚至无需参考文档就能完成开发。

<div align="left"><img src="https://1099326104-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MUvnj-TVDZBXlq-Q9JJ%2F-MWd2QJIlgo02XPN8GP-%2F-MWd2zezzbkwmaqQkf_g%2Fwebview-typescript-demo.png?alt=media&#x26;token=0fd92607-14f7-41d8-98c9-a7c050ec34dc" alt=""></div>

### 多模块支持

在现代化的前端项目中，`esm` 是默认模块导入方式，但我们仍旧支持 `cjs` `umd` 等模块。

### Promise

当前，所有的异步方法都会支持 `Promise`，并有相应的类型标识。

### 社区与反馈

现在我们提供开发者社区的支持，你可以在 GitHub 的讨论区 [创建一个讨论主题](https://github.com/consenlabs/webview/discussions/new) 留下任何有关 WebView 或 DApp 的问题。

## 快速开始

如果你正在寻找一个完整的项目示例，请查看我们准备好的完整项目示例：

* React 项目示例：[examples/react-app](https://github.com/consenlabs/webview/blob/master/examples/react-app)
* Vue 项目示例：[examples/vue-app](https://github.com/consenlabs/webview/tree/master/examples/vue-app)
* UMD 项目示例：[examples/umd](https://github.com/consenlabs/webview/tree/master/examples/umd)

### 安装

建议使用包管理工具下载与安装 `@consenlabs-fe/webview` 。为此，我们的项目需要 [NodeJS](https://nodejs.org/en/download/) 环境与 [NPM](https://www.npmjs.com/) 管理工具。(或是 [Yarn](https://yarnpkg.com/))

**NPM:** (推荐方式)

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

**Yarn:**

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

**CDN:**

&#x20;`@consenlabs-fe/webview` 也支持使用 [unpkg](https://unpkg.com/@consenlabs-fe/webview/dist/index.js) 或 [jsdelivr](https://cdn.jsdelivr.net/npm/@consenlabs-fe/webview/dist/index.min.js) 以 CDN 地址的方式在外部加载 (CDN 同步最新的版本可能需要一些时间)

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

### 引入和使用

在使用 SDK 之前，你需要使用 `import` 引入模块：

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

为了保持兼容性，我们建议你总是在使用前**先判断是否处于 imToken 环境中**：

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

## API 参考

这是所有的 API 和类型参考。事实上如果你正在使用 TypeScript，项目中已经有完善的接口提示。

### 通用

这是根模块携带的静态 API (纯函数)，通常用于检查环境和通用场景的处理。

#### isTokenEnv

检查当前是否处于 imToken WebView 环境中，返回布尔值。

**类型**

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

**使用示例**

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

####

#### getVersion

获取 imToken 应用当前版本。

**类型**

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

**使用示例**

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

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

####

#### isGreaterThanOrEqualVersion

判断 imToken 应用的当前版本是否大于指定值。

**类型**

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

**使用示例**

```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

比较两个版本的值并返回数字。

对比的值必须为[语义化版本](https://semver.org/)的字符串，返回值和对比逻辑与 [JavaScript sort function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) 完全一致。

**类型**

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

**使用示例**

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

// output -> '0'
```

#### isCancelError

检查错误是否为用户取消。

**类型**

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

**使用示例**

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

#### ERRORS

错误常量的集合。大多数场景下不需要直接引用此常量。

**类型**

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

#### apis

与宿主环境进行通信的 API，详见下文。

### device API

#### getCurrentLanguage

获取当前的语言环境，来源于用户在 imToken 应用内的设定。

**类型**

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

**使用示例**

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

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

#### getCurrentCurrency

获取当前的货币编码。

**类型**

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

**使用示例**

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

// output -> 'CNY'
```

###

### native API

提供原生平台 UI 与交互能力。

#### alert

在弹窗中显示字符串。

**类型**

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

**使用示例**

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

####

#### confirm

打开一个确认会话窗口。

用户点击确认或取消后会返回布尔值。

**类型**

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

**使用示例**

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

#### setLoading

设置当前 WebView 为 Loading 状态。

{% hint style="warning" %}
如果你没有主动取消此状态，用户将无法进行任何操作。Loading 状态将会屏蔽用户的行为事件。
{% endhint %}

**类型**

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

**使用示例**

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

#### share

分享链接或是图片。

当分享内容为图片时，需要编码为 `base64` 格式。

是否能够成功分享取决于用户的确认与是否允许权限。

**类型**

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

type ShareParamsImage = {
  title: string
  image: string
}

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

**使用示例**

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

#### scanQRCode

调用摄像头扫描二维码，扫码完成将会返回字符串，失败或取消将抛出错误。

**类型**

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

**使用示例**

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

```

#### setClipboard

粘贴字符串。

**类型**

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

**使用示例**

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

```

###

### navigator API

路由与页面设置。

#### closeDapp

关闭当前 DApp。

**类型**

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

**使用示例**

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

####

#### goBack

返回上一层路由，如果路由栈为空将会关闭 DApp。

**类型**

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

**使用示例**

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

####

#### routeTo

跳转至指定页面。

**类型**

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

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

**使用示例**

```typescript
// Jump to other DApps

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

####

#### getOrientation

获取当前设备的方向信息。

**类型**

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

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

**使用示例**

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

// output -> 'LANDSCAPE'
```

####

#### setOrientation

设置设备方向。

**类型**

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

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

**使用示例**

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

####

#### setTitle

动态设置 DApp 的标题，这仅会影响 WebView 的标题，不会更改 Web 的 `title` 。

**类型**

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

**使用示例**

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

####

### user API

#### showAccountSwitch

展示钱包的切换面板。如果切换成功，新的地址将会被返回。

**类型**

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

**使用示例**

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

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

### layout API

#### setOptions

设置 WebView 的外部框架样式。

这将同步更新当前 WebView 的布局，并且只能在页面被加载和解析后应用。如果你想在页面加载时对布局进行修改，请参考我们的预加载配置文档。

**类型**

```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
```

**使用示例**

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

####

### internal API

未稳定的 API，主要用于高级用户定制开发和调试。
