Introduction
A Vega Web App is a widget built on top of the open-source Chromium web engine. This engine is responsible for parsing and rendering web pages, including HTML, CSS, and JavaScript. For further details, please refer to Vega Web App Overview.
This article explains how to effectively manage the Remote Control back button within the Vega Web App to transmit the specific system key events to your web application’s JavaScript and exit the application.
Overview
The allowSystemKeyEvents
prop controls whether the web application will actively listen for specific system key events, such as the Back button (identified by keyCode: 27).
This functionality helps developers to keep the business logic within the web app to handle the key events directly instead of relying on React Native for Vega app code. When this property is set to true
, specific system key events are delivered directly to the web app’s JavaScript and not in the React Native for Vega app code.
NOTE: Only the most recent WebView instance will receive system key events, even if other WebView instances are on the screen.
For the list of supported remote control key events and the associated key codes, please refer to this documentation.
The onCloseWindow
method notifies the React Native for Vega app to close the given WebView and remove it from the view system if necessary, when your web app triggers the Window.close()
method.
Since any WebView interaction after this call may result in unexpected behaviour, the host (React Native for Vega) app should destroy the WebView instance after receiving this call.
The following example illustrates the typical usage of the functionalities in the Vega Web App. The allowSystemKeyEvents
prop is set to true
, which allows the web app to directly receive and handle the system key events, such as the Back button. The onCloseWindow
event handler is used to close the WebView and exit the app when the Window.close()
method is invoked from the web app.
import React, { useEffect, useRef } from 'react';
import { BackHandler, StyleSheet, View } from 'react-native';
import { WebView } from '@amzn/webview';
export const App = () => {
const webRef = useRef(null);
// Note: the Style flex/container that is defined for the View element
// is essential to get the focus into WebView.
const styles = StyleSheet.create({
sectionContainer: {
flex: 1,
},
});
// Handle the close event raised from the loaded webpage,
// destroy the WebView instance after receiving this call
const handleOnCloseWindow = () => {
console.log('[onCloseWindow] Exiting the app...');
BackHandler.exitApp();
};
return (
<View style={styles.sectionContainer}>
<WebView
ref={webRef}
source={...}
allowSystemKeyEvents={true}
hasTVPreferredFocus={true}
javaScriptEnabled={true}
...
onCloseWindow={handleOnCloseWindow}
/>
</View>
);
};