React Native 中的 WebView 整页截图
Posted
技术标签:
【中文标题】React Native 中的 WebView 整页截图【英文标题】:WebView Full Page Screenshot in React Native 【发布时间】:2020-09-02 15:00:06 【问题描述】:如何在 react native 中截取 webview 的整页截图?已经尝试过“react-native-view-shot”Link,但它只截取可见区域的屏幕截图。 有人请帮忙。 谢谢
【问题讨论】:
您找到解决方案了吗?我也有同样的问题 @SritejaSugoor 请找到以下答案。谢谢 【参考方案1】:对于未来的读者: 下面是经过多次尝试后的最终脚本,它从 Webview 截取了整页截图。我使用 ProgressWebView 而不是 Webview。如果需要,您可以使用 Webview。 此代码适用于功能组件。 注意:当页面完全加载后,点击Take Screenshot按钮
import React, useState from 'react';
import View, Button from 'react-native';
import captureRef from "react-native-view-shot";
import ProgressWebView from "react-native-progress-webview";
import json5 from 'json5'
import Dimensions from 'react-native';
const Report = () =>
const [componentHeight, setComponentHeight] = useState(0)
const [globalComponentHeight, setGlobalComponentHeight] = useState(0)
const [componentHeightFlex, setComponentHeightFlex] = useState(1)
let url = 'https://***.com/questions/63708244/webview-full-page-screenshot-in-react-native'
let webview = null;
let count = 0
const injectJS = _ =>
const script = `
let method$count = _ =>
let documentHeight = document.body.scrollHeight
let data = componentHeight: documentHeight
window.ReactNativeWebView.postMessage(JSON.stringify(data))
method$count()`
webview.injectjavascript(script)
count++
const takeScreenshot = _ =>
console.log(globalComponentHeight)
const height = Dimensions.get("window")
console.log(height)
if(globalComponentHeight <= height) setComponentHeight(height)
else setComponentHeight(globalComponentHeight)
setComponentHeightFlex(null)
setTimeout(_ =>
captureRef(webview,
format: "png",
quality: 0.9,
result: "base64"
).then(
_screenshot =>
console.log(_screenshot)
//First save your screenshot from _screenshot(base64 string). You can send base64 string to your server and save
//Then make the component default as below
setComponentHeight(0)
setComponentHeightFlex(1)
,
error => console.error("Oops, screenshot failed", error)
);
, 100)
return (
<View style= marginTop: 40, flex: 1, display: 'flex' >
<Button mode='contained' onPress=takeScreenshot title="Take Screenshot"/>
<View
style=
height: componentHeight,
flex: componentHeightFlex
>
<ProgressWebView
ref=ref =>
if (ref != null)
webview = ref
bounces=false
style= position: 'relative'
showsHorizontalScrollIndicator=false
showsVerticalScrollIndicator=true
source= uri: url
startInLoadingState=true
onLoad=e => injectJS()
onMessage=e =>
let data = json5.parse(e.nativeEvent.data)
// console.log(data)
setGlobalComponentHeight(parseInt(data.componentHeight))
></ProgressWebView>
</View>
</View>
);
export default Report
【讨论】:
以上是关于React Native 中的 WebView 整页截图的主要内容,如果未能解决你的问题,请参考以下文章
从 React Native App 中的 WebView 打开动态链接
使用 WebView React Native 播放本地文件中的视频
React-Native-Webview:预期nodeHandle不为null