首页 文章

React Native WebView Cross原始请求仅支持协议方案:http,data,chrome,https

提问于
浏览
0

我们正在尝试在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错误?

Environment

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

1 回答

  • 0

    按照核心团队成员的建议解决问题 . WebView has been moved to 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中工作没有任何问题 .

相关问题