gpt4 book ai didi

android - 如何为 react 原生的 android WebView 设置允许文件访问?

转载 作者:搜寻专家 更新时间:2023-11-01 08:25:27 24 4
gpt4 key购买 nike

我想在我使用 react-native 的内置 WebView 组件创建的 Android WebView 中禁用文件访问。

Android WebView docs说“默认情况下启用文件访问。”,这对我的组织来说是一个安全问题。

react-native 0.31 docs提及可用于访问底层 WebView 节点的 getWebViewHandle 方法;如果这有效,那么我可以(大概)写:

import { WebView, Platform } from 'react-native';
//...
var reactWebview = <Webview [props here] />
if (Platform.OS === 'android') {
var webview = reactWebview.getWebViewHandle();
webview.setAllowFileAccess(false);
}

但是,react-native docs 的更高版本不要提及 getWebViewHandle,当我在 Android 设备上的 react-native 0.44 中运行这样的代码时,我收到错误消息 webview.getWebViewHandle is not a function

我的问题是:

  1. react-native 创建的 Android WebView 是否默认启用文件访问?

  2. 如果是这样,我们如何禁用此文件访问权限?我们可以通过扩展 WebView 类来实现这一点,还是需要 fork 和修改 react-native?

感谢您的宝贵时间!

最佳答案

问题一:从ReactWebViewManager.java的源码看,RN 不调用 WebView.setAllowFileAccess,因此文件访问是由 Android WebView 启用的,而不是由 RN 启用的。

问题 2:您可以创建自定义 WebView 来执行您需要的操作,或者只是从 Native Module 中获取 WebView 的引用, 那么你就可以在Native Module中访问Android WebView的所有api,比如setAllowFileAccess .

原生模块

public class WebViewSettingModule extends ReactContextBaseJavaModule {

public WebViewSettingModule(ReactApplicationContext reactContext) {
super(reactContext);
}

@Override
public String getName() {
return "WebViewSetting";
}

@ReactMethod
public void setWebView() {

Activity activity = getCurrentActivity();
//the id for the ReactRootView is always be 1
@IdRes int id = 1;
View view = activity.findViewById(id);
if (view instanceof ReactRootView) {
ReactRootView reactRootView = (ReactRootView) view;
//make sure the WebView is directly child of ReactRootView
reactRootView.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
@Override
public void onChildViewAdded(View parent, final View child) {
if (child instanceof WebView) {
Log.e("onChildViewAdded: ", ((WebView) child).getUrl());
//get the reference to the WebView and setAllowFileAccess
((WebView) child).getSettings().setAllowFileAccess(false);
}
}

@Override
public void onChildViewRemoved(View parent, View child) {

}
});
}
}
}

index.android.js

import React, {Component} from "react";
import {AppRegistry, View, WebView} from "react-native";
//the native module
import MyWebView from "./src/MyWebView";

export default class WebViewSetting extends Component {

componentDidMount() {
//notify native code to modify WebView setting
MyWebView.setWebView();
}

render() {
return (
<View style={{flex: 1}}>
<WebView
source={{uri: 'https://github.com/'}}
style={{marginTop: 20}}/>
</View>
);
}
}


AppRegistry.registerComponent('WebViewSetting', () => WebViewSetting);

完整代码可以在here中找到

关于android - 如何为 react 原生的 android WebView 设置允许文件访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45766494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com