问题
I am using a React Native WebViw in my app. I want to disable download of files. Mostly just documents. I cant disable storage permissions as certain features in the app need this feature.
回答1:
You can achieve this by injecting a javascript, with the help of controlsList="nodownload" property check below reference code for video file:
<WebView
style={{
height: this.props.videoPlayerHeight,
width: this.props.videoPlayerWidth,
backgroundColor: 'black',
}}
allowsFullscreenVideo={true}
allowFileAccess={false}
mixedContentMode="always"
mediaPlaybackRequiresUserAction={true}
injectedJavaScript={`document.getElementsByTagName("video")[0].controlsList="nodownload";`}
source={{uri: `${this.props.videoLink}#t=0.01`}}
startInLoadingState={true}
renderLoading={this.renderLoading}
/>
回答2:
Unfortunately there is no simple setting for this. But at least one workaround is fairly straightforward.
Implement an onShouldStartLoadWithRequest
handler. If you return false
from this handler, the WebView will not load the URL. You can then decide if you want a simple implementation that just looks for "file-like URLs" or does something more clever. A very naive implementation:
<WebView
ref={r => this._webView = r}
source={{ uri }}
onShouldStartLoadWithRequest={this.checkLoadRequest}
onNavigationStateChange={this.checkLoadRequest}
/>
...
checkLoadRequest(navigator) {
const url = navigator.url.toLowerCase();
// VERY naive implementation but might be all you wanted
if (url.indexOf('.pdf') > -1 || url.indexOf('.doc') > -1) {
// On iOS we just return false.
// Android requires us to call stopLoading().
this._webView.stopLoading();
return false;
}
return true;
}
For a more sophisticated implementation option, you could use a regex to detect more file-extension patterns you want to block.
Note that this handler cannot be async and work properly cross-platform. A hack if you want to do something MUCH more sophisticated (e.g. make a HEAD request to the URL invisibly behind the scenes to see what it's going to send back) you could just block/reject all requests, do your magic, then programmatically tell the webview to navigate to the URL if it's OK. It will make navigation very slow in most cases, but is very accurate.
来源:https://stackoverflow.com/questions/60144154/disable-download-in-react-native-webview