VK Connect
A package for integrating VK Mini Apps with official VK clients for iOS, Android and Web.
Usage
import connect from '@vkontakte/vk-connect';
connect.send('VKWebAppInit');
connect.subscribe(e => console.log(e));
For use in a browser, include the file dist/index.umd.js and use as follows
<script src="dist/index.umd.js"></script>
<script>
vkConnect.send('VKWebAppInit');
</script>
API Reference
connect.send(method[, params])
Sends a message to native client and returns the Promise object with response data
Parameters
method required The VK Connect method
params optional Message data object
Example
connect
.send('VKWebAppGetEmail')
.then(data => {
console.log(data.email);
})
.catch(error => {
});
You can also use imperative way
try {
const data = await connect.send('VKWebAppGetEmail');
console.log(data.email);
} catch (error) {
}
connect.subscribe(fn)
Subscribes a function to events listening
Parameters
fn required Function to be subscribed to events
Example
connect.subscribe(event => {
if (!event.detail) {
return;
}
const { type, data } = event.detail;
if (type === 'VKWebAppOpenCodeReaderResult') {
console.log(data.code_data);
}
if (type === 'VKWebAppOpenCodeReaderFailed') {
console.log(data.error_type, data.error_data);
}
});
connect.send('VKWebAppOpenCodeReader', {});
connect.unsubscribe(fn)
Unsubscribes a function from events listening
Parameters
fn required Event subscribed function
Example
const fn = event => {
};
connect.subscribe(fn);
connect.unsubscribe(fn);
connect.supports(method)
Checks if an event is available on the current device
Parameters
method required The VK Connect method
connect.isWebView()
Returns true if VK Connect is running in mobile app, or false if not
Middleware API
Middlewares are pieces of code that intercept and process data between sending and receiving. Thus, by creating middlewares, you can easily log data, modify data before sending it, talking to an asynchronous API, etc. If you've used Redux, you were also probably already familiar with the concept—a similar is used here.
applyMiddleware(middleware1, ..., middlewareN)
Creates the VK Connect enhancer that applies middleware to the send
method. This is handy for a variety of task such as logging every sent
event. Returns the VK Connect enhancer applying the middleware.
Parameters
middlewareN A middleware to be applied
Example
import connect, { applyMiddleware } from '@vkontakte/vk-connect';
const logger = ({ send, subscribe }) => next => async (method, props) => {
const result = await next(method, props);
console.log(result);
return result;
};
const enhancedConnect = applyMiddleware(logger)(connect);