2.0.0 • Published 4 years ago

@vite/bridge v2.0.0

Weekly downloads
3
License
ISC
Repository
github
Last release
4 years ago

Vite Javascript Bridge

A javascript bridge between native & web, can be used in web page in Vite App.

v2.0.x require Vite App version 3.2.0 and above.

Quick start

import Bridge from '@vite/bridge'

const bridge = new Bridge()

bridge['wallet.currentAddress']().then(address => {
    console.log(`current address is ${address}`)
})

Installation

With bundler, like: webpack, rollup.

# use npm
npm install @vite/bridge --save

# use yarn
yarn add @vite/bridge

Or you can include dist/bridge.js in HTML.

<script src="/path/to/bridge.js"></script>

Usage

import Bridge from '@vite/bridge'

const bridge = new Bridge()

bridge['bridge.version']().then(data => {
    console.log(data)
})

If you include bridge.js in your HTML, Usage refer following code:

<script>
    const bridge = new ViteBridge();
</script>

Constructor options

Bridge constructor can receive options, which is very different between version 2.0.x and version 1.x

2.0.x

You can pass in a function, will be invoked after bridge inited.

const bridge = new Bridge(bridge => {
    // will be invoked after bridge inited
})

1.x

You can pass in an options object.

  • options.readyCallback

A function will be invoked after bridge inited

  • options.selfDefinedMethods

A string array, each string is a method name which has been supported by Vite App, but not in ViteBridge internal methods list. So you can extend ViteBridge these methods.

Mostly you don't need this property.

const bridge = new Bridge({
    readyCallback: bridge => {},
    selfDefinedMethods: [
        // strings
    ]
})

Static properties

You can use static properties like Bridge.enabled

NameTypeDescriptionComment
enabledbooleanis in vite appadded in version 2.0.0
_supportBooleanis supporteddeprecated in version 2.0.0
_inIosContainerBooleanis in iOS system | deprecated in version 2.0.0
_inAndroidContainerBooleanis in Android system | deprecated in version 2.0.0

Instance Methods

There are some methods on Bridge instance. Each method return a promise, so you can invoke like:

bridge[methodName](params).then(res => {
    console.log(`get result from native Vite App: ${JSON.stringify(res)}`)
}, err => {
    console.error(`failed to invoke ${methodName}: ${JSON.stringify(err)}`)
})

Available Methods list in following table.

Input param is passed in method, and Output param is return from native Vite App.

Method nameInput paramOutput paramDescriptionComment
bridge.versionvoidtypes.BridgeVersionget js bridge versionoutput like: { "versionName": "1.1.0", "versionCode": 2}
app.infovoidtypes.AppInfoget Vite App versionoutput like: {"platform":"ios", "versionName":"1.0.0", "versionCode":1024} platform is ios or android
app.languagevoid"zh" or "en"get Operation System language
app.setWebTitletypes.SetWebTitleInputvoidset webview titleinput like: { "title": "Vite Cool" }
app.sharetypes.ShareLinkInputvoidshare a linkinput like: { url: "https://vite.org" }
app.setRRButtontypes.SetRRButtonInputvoidshow an icon (size: 56px * 56px, base64 Data URL) or customized text, no more than 4 chars, in right nav buttoninput like {"img": "data:image/png;base64, xxxx"} or {"text": "Vite"}
wallet.currentAddressvoidstringget current used vite address
wallet.sendTxByURItypes.SendTxInputtypes.SendTxOutputsend a txsee following example
app.scanvoidtypes.ScanOutputscan a QR code by cameranew in version 2.0.0output like: {"text": "Vite Cool"}
callstring, ...anyanyinvoke a native methodnew in version 2.0.0

Use call if bridge missing some native method. for example: Vite App add new methods, but bridge haven't update, call is helpful.

example

Set webview title.

bridge['app.setWebTitle']({
    "title": "Vite Cool"
}).then(() => {
    console.log(`success`)
}, ({ code, msg, data }) => {
    console.error(`failed to set webview title: [${code}] ${msg}, native response: ${data}`)
})

Error detail will be described in following section, just ignore for now.

Send a transaction by Vite Bridge.

The uri should be a Vite URI, can be generated by @vite/vitejs

import * as utils from "@vite/vitejs-utils";
import * as abi from "@vite/vitejs-abi";

// regular transfer
const sendTx = await bridge["wallet.sendTxByURI"]({
    address: currentWalletAddress,
    uri: utils.uriStringify({
        target_address: receiverAddress,    // receiver address
        params: {
            tti: 'tti_5649544520544f4b454e6e40',    // tokenId, usually is VITE
            amount: amount, // in VITE unit
        }
    })
})

// call contract method
const hexFunctionCall = abi.encodeFunctionCall(contractMethodABI, contractMethodParams);
const base64FunctionCall = utils._Buffer.from(hexFunctionCall, 'hex').toString('base64');
const sendTx = await bridge["wallet.sendTxByURI"]({
    address: currentWalletAddress,
    uri: utils.uriStringify({
        target_address: contractAddress,    // contract address
        function_name: contractMethodName,  // contract method name
        params: {
            tti: 'tti_5649544520544f4b454e6e40',    // tokenId
            amount: amount, // in VITE unit
            data: base64FunctionCall,
        }
    })
})

Call a method

bridge.call('app.setWebTitle', {
    "title": "Vite Cool"
})

subscribe events

Vite Bridge can subscribe following events trigged by user.

Event nameDescription
nav.RRBtnClickthe right button in navbar been clicked
page.onShowpage is show in the screen, or Vite App is switch to the frontground
shakeGesturephone shaked

subscribe

Subscribe an event

bridge.subscribe(event_name, event_handler, once)

When the event trigged, the event handlers will be invoked in the order of subscribe.

The third param once is optional, default is false. If true, the event_handler will be invoked only once.

Example:

bridge.subscribe('nav.RRBtnClick', () => {
    console.log(`navbar right button clicked`)
})

bridge.subscribe('page.onShow', () => {
    console.log(`resume animation`)
})

// you can subscribe an event multiple times, but not recommended.
bridge.subscribe('page.onShow', () => {
    console.log(`Welcome back`)
})

unsubscribe

Unsubscribe an event

bridge.unsubscribe(event_name, event_handler)

The second param event_handler is optional, if omited, bridge will unsubscribe all event_handlers on the specific event.

caveat: the event_handler should equal with the one passed in subscribe

Example

const fn = () => {
    console.log(`Welcome back`)
}

bridge.subscribe('page.onShow', fn)

bridge.unsubscribe('page.onShow', fn)

// unsubscribe all event_handler on event page.onShow
bridge.unsubscribe('page.onShow')

Anonymous event_handler can't be unsubscribed

bridge.subscribe('page.onShow', () => {
    console.log(`resume animation`)
})

// unsubscribe failed, because this anonymous event_handler is not the former one passed in subscribe
bridge.unsubscribe('page.onShow', () => {
    console.log(`resume animation`)
})

Error

common error code

CodeDescription
1unknown error
2invalidate params
3network error
4login error
5address in params not identical to current address

wallet.sendTxByURI

wallet.sendTxByURI could throw following codes.

CodeDescriptionComment
4001duplicate transaction before last transaction finishedonly can send next transaction after the previous one be handled
4002cannot find related tokenId
4003amount format error (should be translate to min unit)
4004user suspend
2.0.0

4 years ago

1.0.14

5 years ago

1.0.13

5 years ago

1.0.13-7

5 years ago

1.0.13-5

5 years ago

1.0.13-4

5 years ago

1.0.13-3

5 years ago

1.0.13-2

5 years ago

1.0.13-0

5 years ago

1.0.12

5 years ago

1.0.11

5 years ago

1.0.10-4

5 years ago

1.0.10-3

5 years ago

1.0.10-2

5 years ago

1.0.10-1

5 years ago

1.0.10-0

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.1-2

5 years ago

1.0.1-1

5 years ago

1.0.1-0

5 years ago

1.0.0

5 years ago