react native中基于webview的腾讯图形验证码
- 效果实例图
- 第三方库
腾讯验证码
效果实例图
第三方库
npm i react-native-webview
react-native-webview
import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { WebView } from 'react-native-webview';
const TestWebViewCode = () => {
const [params, setParams] = useState(null);
const handleMessage = event => {
const data = JSON.parse(event.nativeEvent.data);
// 处理从WebView发送过来的消息
console.log('[]', data);
// 在这里可以处理JavaScript回调函数返回的值
setParams(() => data?.randstr)
};
useEffect(() => {
return () => { };
}, []);
return (
<>
<WebView
javaScriptEnabled={true}
source={{
html: `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web 前端接入示例</title>
<!-- 验证码程序依赖(必须)。请勿修改以下程序依赖,如通过其他手段规避加载,会导致验证码无法正常更新,对抗能力无法保证,甚至引起误拦截。 -->
<script src="https://turing.captcha.qcloud.com/TCaptcha.js"></script>
<style type="text/css">
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
</style>
</head>
<body></body>
<script>
// 定义回调函数
function callback(res) {
console.log('callback:', res);
window.ReactNativeWebView.postMessage(JSON.stringify(res))
}
// 定义验证码js加载错误处理函数
function loadErrorCallback() {
var appid = '1';
var ticket = 'trerror_1001_' + appid + '_' + Math.floor(new Date().getTime() / 1000);
callback({
ret: 0,
randstr: '@' + Math.random().toString(36).substr(2),
ticket: ticket,
errorCode: 1001,
errorMessage: 'jsload_error'
});
}
window.onload = function() {
try {
var captcha = new TencentCaptcha('1', callback, {
userLanguage: 'zh-cn',
type:'embed',
showFn: (ret) => {
const {
duration, // 验证码渲染完成的耗时(ms)
sid, // 链路sid
} = ret;
}
});
captcha.show();
} catch (error) {
loadErrorCallback();
}
}
</script>
</html>
`
}}
onMessage={handleMessage}
/>
<Text>返回参数:{params}</Text>
</>
);
};
const styles = StyleSheet.create({
});
export default TestWebViewCode;