react-native-webview#WebViewMessageEvent TypeScript Examples
The following examples show how to use
react-native-webview#WebViewMessageEvent.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CredentialGenerator.tsx From jellyfin-audio-player with MIT License | 6 votes |
handleMessage = (event: WebViewMessageEvent) => {
// GUARD: Something must be returned for this thing to work
if (!event.nativeEvent.data) {
return;
}
// Parse the content
const data = JSON.parse(event.nativeEvent.data);
if (!data.deviceId
|| !data.credentials?.Servers?.length
|| !data.credentials?.Servers[0]?.UserId
|| !data.credentials?.Servers[0]?.AccessToken) {
return;
}
// If a message is received, the credentials should be there
const { credentials: { Servers: [ credentials ] }, deviceId } = data;
this.props.onCredentialsRetrieved({
uri: credentials.ManualAddress,
user_id: credentials.UserId,
access_token: credentials.AccessToken,
device_id: deviceId,
});
};
Example #2
Source File: quill-editor.tsx From react-native-cn-quill with MIT License | 5 votes |
private onMessage = (event: WebViewMessageEvent) => {
const message = this.toMessage(event.nativeEvent.data);
const { autoSize } = this.props;
const response = message.key
? this._promises.find((x) => x.key === message.key)
: undefined;
switch (message.type) {
case 'dimensions-change':
if (autoSize === true) this.setState({ height: message.data.height });
this._handlers
.filter((x) => x.event === message.type)
.forEach((item) => item.handler(message.data));
break;
case 'format-change':
case 'text-change':
case 'selection-change':
case 'html-change':
case 'editor-change':
case 'blur':
case 'focus':
this._handlers
.filter((x) => x.event === message.type)
.forEach((item) => item.handler(message.data));
break;
case 'has-focus':
case 'get-contents':
case 'get-text':
case 'get-length':
case 'get-bounds':
case 'get-selection':
case 'get-dimensions':
case 'get-html':
case 'get-format':
case 'get-leaf':
case 'remove-format':
case 'format-text':
if (response) {
response.resolve(message.data);
this._promises = this._promises.filter((x) => x.key !== message.key);
}
break;
default:
// Allow catching messages using the passed webview props
if (this.props.webview?.onMessage) {
this.props.webview?.onMessage(event);
}
}
};
Example #3
Source File: GoogleTimeLine.tsx From hamagen-react-native with MIT License | 4 votes |
GoogleTimeLine = ({ strings, toggleWebview, onCompletion }: GoogleTimeLineProps) => {
const {
general: { additionalInfo },
locationHistory: { beforeCheckTitle, beforeCheckDesc, beforeCheckDesc2, beforeCheckButton, skip, successFoundTitle, successFoundDesc, successFoundButton, successNotFoundTitle, successNotFoundDesc, successNotFoundButton, failedTitle, failedDesc, failedButton }
} = strings;
const didRetry = useRef<boolean>(false);
const webViewRef = useRef<WebView>(null);
const [{ openWebview, isLoggedIn, state }, setState] = useState<State>({ openWebview: false, isLoggedIn: false, state: 'before' });
const pageStateConfig = () => {
switch (state) {
case 'before': {
return {
icon: require('../../assets/locationHistory/before.png'),
title: beforeCheckTitle,
desc1: beforeCheckDesc,
desc2: beforeCheckDesc2,
button: beforeCheckButton,
action: () => setState(prevState => ({ ...prevState, openWebview: true }))
};
}
case 'successFound': {
return {
icon: require('../../assets/locationHistory/successFound.png'),
title: successFoundTitle,
desc1: successFoundDesc,
desc2: '',
button: successFoundButton,
action: () => onCompletion()
};
}
case 'successNotFound': {
return {
icon: require('../../assets/locationHistory/successNotFound.png'),
title: successNotFoundTitle,
desc1: successNotFoundDesc,
desc2: '',
button: successNotFoundButton,
action: () => onCompletion()
};
}
case 'failed': {
return {
icon: require('../../assets/locationHistory/failed.png'),
title: failedTitle,
desc1: failedDesc,
desc2: '',
button: failedButton,
action: () => setState(prevState => ({ ...prevState, openWebview: true }))
};
}
default: { return { icon: 0, title: '', desc1: '', desc2: '', button: '', action: () => { } }; }
}
};
const retryKMLDownload = (didRetry: any, kmlUrls: string[]) => new Promise<string[]>((resolve) => {
setTimeout(async () => {
didRetry.current = true;
resolve(await Promise.all(kmlUrls.map(url => fetch(url).then(r => r.text()))));
}, IS_IOS ? 5000 : 10);
});
const onMessage = async ({ nativeEvent: { data } }: WebViewMessageEvent) => {
if (!data) {
return;
}
if (data === 'LOGGED_IN' && !isLoggedIn) {
try {
webViewRef.current?.injectJavaScript(`document.getElementsByTagName(\'html\')[0].innerHTML = \'${getLoadingHTML()}\'; true;`);
setState(prevState => ({ ...prevState, isLoggedIn: true }));
const kmlUrls = getLastNrDaysKmlUrls();
let texts = await Promise.all(kmlUrls.map(url => fetch(url).then(r => r.text())));
if (texts[0].indexOf('DOCTYPE') > -1 && texts[0].indexOf('Error') > -1) {
if (!didRetry.current) {
texts = await retryKMLDownload(didRetry, kmlUrls);
if (texts[0].indexOf('DOCTYPE') > -1 && texts[0].indexOf('Error') > -1) {
return onFetchError('Fetch KML error');
}
} else {
return onFetchError('Fetch KML error');
}
}
const pointsData = texts.flatMap((kml: string) => kmlToGeoJson(kml));
if (pointsData.length === 0) {
return onFlowEnd('successNotFound');
}
await insertToSampleDB(pointsData);
return onFlowEnd('successFound');
} catch (error) {
await onFetchError(error);
}
}
};
const onFetchError = async (error: any) => {
await onFlowEnd('failed');
onError({ error });
};
const onFlowEnd = async (state: 'before' | 'successFound' | 'successNotFound' | 'failed') => {
if (state !== 'failed') {
// once 14 days flow completed for the first time
await AsyncStorage.setItem(SHOULD_HIDE_LOCATION_HISTORY, 'true');
store().dispatch(checkIfHideLocationHistory());
}
webViewRef.current?.injectJavaScript('setTimeout(() => { document.location = "https://accounts.google.com/logout"; true; }, 10)');
setTimeout(async () => {
didRetry.current = false;
setState(prevState => ({ ...prevState, openWebview: false, isLoggedIn: false, state }));
await CookieManager.clearAll(true);
}, 300);
};
return (
<View style={styles.container}>
<View style={styles.textsContainer}>
{
(!IS_SMALL_SCREEN || state !== 'before') && (
<Icon source={pageStateConfig().icon} width={154} height={64} customStyles={{ marginBottom: 50 }} />
)
}
<Text style={styles.title} bold>{pageStateConfig().title}</Text>
<Text style={{ marginBottom: 20 }}>{pageStateConfig().desc1}</Text>
<Text bold>{pageStateConfig().desc2}</Text>
</View>
{
state === 'before' && (
<View style={{ width: SCREEN_WIDTH * 0.7, alignItems: 'center' }}>
<TouchableOpacity onPress={() => toggleWebview(true, USAGE_PRIVACY)}>
<Text style={{ fontSize: 14 }}>{additionalInfo}</Text>
<View style={styles.bottomBorder} />
</TouchableOpacity>
</View>
)
}
<View style={{ alignItems: 'center' }}>
<ActionButton text={pageStateConfig().button} onPress={pageStateConfig().action} containerStyle={{ marginBottom: 15 }} />
<View style={{ height: 20 }}>
{
(state === 'before' || state === 'failed') && (
<TouchableOpacity onPress={onCompletion}>
<Text style={{ fontSize: 20 }}>{skip}</Text>
</TouchableOpacity>
)
}
</View>
</View>
<FetchHistoryModal
webViewRef={webViewRef}
isVisible={openWebview}
onMessage={onMessage}
isLoggedIn={isLoggedIn}
closeModal={() => setState(prevState => ({ ...prevState, openWebview: false }))}
/>
</View>
);
}