我们正尝试在Android React Native WebView 中使用Angular JS和HTMl加载SPA应用。该解决方案在Dev服务器上运行良好,但是当我们尝试在调试中加载它并发布版本时,它会引发以下错误。我们已经在chrome中对其进行了调试,发现除html文件外,所有资源都正在加载。只有Index.html文件正在加载。
控制台错误:
Failed to load file:///android_asset/template.html:
Cross origin requests are only supported for protocol schemes: http, data, chrome, https.
我们正在RN WebView中加载本地html文件:
<WebView
ref="webview"
scalesPageToFit={true}
source={{uri: 'file:///android_asset/www/index.html'}}
javaScriptEnabled={true}
domStorageEnabled={true}
nativeConfig={{props: {webContentsDebuggingEnabled: true}}}
setAllowFileAccessFromFileURLs={true}
setAllowUniversalAccessFromFileURLs={true}
/>
我们尝试在此路径下更改 ReactWebViewManager.java
MyReactProjectName \ node_modules \ react-native \ ReactAndroid \ src \ main \ java \ com \ facebook \ react \ views \ webview \ ReactWebViewManager.java 我们进行了以下更改:
settings.setDomStorageEnabled(true);
settings.setAllowFileAccess(true);
settings.setAllowContentAccess(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
settings.setAllowFileAccessFromFileURLs(true);
setAllowUniversalAccessFromFileURLs(webView, true);
}
尝试按照here中所述的解决方案进行操作,但仍然无法加载所需的HTML文件。
有什么方法可以更改 ReactWebViewManager.java 以进行本地文件访问,因为RN WebView无法找到本地HTML文件并抛出CORS错误?
环境
React Native Environment Info:
System:
OS: macOS High Sierra 10.13.6
CPU: x64 Intel(R) Core(TM) i3 CPU 540 @ 3.07GHz
Memory: 125.40 MB / 12.00 GB
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 9.5.0 - /usr/local/bin/node
Yarn: 1.10.1 - ~/.yarn/bin/yarn
npm: 6.4.1 - /usr/local/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
SDKs:
iOS SDK:
Platforms: iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 5.0
IDEs:
Android Studio: 3.0 AI-171.4443003
Xcode: 10.0/10A255 - /usr/bin/xcodebuild
npmPackages:
react: 16.5.0 => 16.5.0
react-native: 0.57.1 => 0.57.1
npmGlobalPackages:
create-react-native-app: 1.0.0
react-native-cli: 2.0.1
react-native-git-upgrade: 0.2.7
答案 0 :(得分:0)
根据核心团队成员的建议解决问题。 WebView已移至https://github.com/react-native-community/react-native-webview
$ yarn add react-native-webview
$ react-native link react-native-webview
从 react-native-webview 导入WebView组件,并像这样使用它:
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { WebView } from 'react-native-webview';
// ...
class MyWebComponent extends Component {
render() {
return (
<WebView
source={{ uri: 'https://infinite.red/react-native' }}
style={{ marginTop: 20 }}
/>
);
}
}
以上内容可在Android系统中正常使用。