在react native中,如何获取webview中的某个标签的内容,例如:
在webview中,加载baidu.com,我要获取这个页面中选择器为#s_menu_mine的innerText.
这是我当前尝试的代码,gpt给我的,但是这并不能触发handleMessage,即使触发了,我也不确定方法内的代码是否正确,代码如下:
import React, { useState, useRef } from 'react';
import { View, StyleSheet, Alert } from 'react-native';
import { WebView } from 'react-native-webview';
const MyWebViewComponent = () => {
const webViewRef = useRef(null);
const handleLoadEnd = (syntheticEvent) => {
const jsCode = `
document.querySelector('#share-desc').textContent;
`;
webViewRef.current.injectJavaScript(jsCode);
console.log(webViewRef.current)
};
const handleMessage = (event) => {
console.log(event)
const content = event.nativeEvent.data;
setWebContent(content);
Alert.alert(content);
};
return (
<View style={styles.container}>
<WebView
ref={webViewRef}
source={{ uri: 'https://www.realmaster.cn/getapp' }}
onLoadEnd={handleLoadEnd}
onMessage={handleMessage}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export default MyWebViewComponent;