我选择了选项 2,但遇到了 Google 文档查看器错误,所以我做了这个 hacky 的事情来检查是否没有加载内容以刷新 webview。
const retries = 10
const PdfViewerScreen = ({ route, navigation }: Props) => {
const { pdfUrl } = route.params || {}
const webview = useRef(null)
const [tries, setTries] = useState(1)
const [reset, setReset] = useState(Date.now())
const isAndroid = Platform.OS === 'android'
const base = !isAndroid
? ''
: 'https://docs.google.com/gview?embedded=true&url='
// Use date as reset to be able to
// reload the webview
const uri = `${base}${pdfUrl}?t=${reset}`
// Js code to get baseURI when
// webview is loaded. docs.google.com has a bug
// where no content is returned.
const myInjectedJs = `
(function(){
window.ReactNativeWebView.postMessage(window.document.baseURI);
})();`
const onMessage = (event: WebViewMessageEvent) => {
// Issue does not occur in iOS
if(!isAndroid) return
const baseURI = event.nativeEvent.data
if (tries === retries) navigation.goBack()
if (baseURI !== uri) {
setReset(Date.now())
setTries(tries + 1)
}
}
return (
<>
<WebView
ref={webview}
javaScriptEnabled={true}
domStorageEnabled={true}
startInLoadingState={true}
style={tailwind(`flex-1`)}
injectedJavaScript={myInjectedJs}
source={{ uri }}
onMessage={onMessage}
renderLoading={() => (
<View style={tailwind('w-full h-full')}>
<Loading />
</View>
)}
/>
</>
)
}