在 React 原生 WebView 中禁用下载



我在我的应用程序中使用了 React Native WebViw。我想禁用文件下载。大多只是文件。我无法禁用存储权限,因为应用程序中的某些功能需要此功能。

您可以通过注入 javascript 来实现这一点,在 controlsList="nodownload" 属性的帮助下,检查以下视频文件的参考代码:

<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}
/>

不幸的是,没有简单的设置。但至少有一种解决方法相当简单。

实现onShouldStartLoadWithRequest处理程序。如果从此处理程序返回false,则 Web 视图将不会加载 URL。然后,您可以决定是想要一个简单的实现,只查找"类似文件的URL",还是做一些更聪明的事情。一个非常幼稚的实现:

<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;
}    

对于更复杂的实现选项,您可以使用正则表达式来检测要阻止的更多文件扩展名模式。

请注意,此处理程序不能是异步的,也不能跨平台正常工作。如果你想做一些更复杂的事情(例如,在幕后向 URL 发出 HEAD 请求以查看它将发回的内容(,您可以阻止/拒绝所有请求,施展你的魔术,然后以编程方式告诉 Web 视图导航到 URL,如果没问题。在大多数情况下,它会使导航非常慢,但非常准确。

<WebView
scrollEnabled={false}
javaScriptEnabled={true}
allowsFullscreenVideo={true}
userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 
(KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"
source={{uri: htmlAttribs.src}}
mediaPlaybackRequiresUserAction={true}
injectedJavaScript={`document.getElementsByTagName("video")[0].controlsList="nodownload";`}
style={{flex: 1, width: '100%', aspectRatio: 16.0 / 9.0}}
/>

<WebView
source={{ uri: url }}
onShouldStartLoadWithRequest={(res)=>{
if (res.navigationType !== 'other') {
return false
} else {
return true
}
}}/>

最新更新