Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react native webview load from device local file system

I'm trying to load .html, .js, .css files from device's local file system into React Native WebView component. I was able to get the path to the index.html file but specifying this as the url for the WebView simply throws an error. How would I go about this? Please help!

like image 528
Wonil Suh Avatar asked Nov 03 '15 18:11

Wonil Suh


2 Answers

In react native it is now possible to require an HTML file and use it as the source for the web view like this (the path is relative to the react-native file you use it in):

const webapp = require('./webapp/index.html');

and the use it in the WebView like this:

<WebView source={webapp} />

Unfortunately this does not load CSS and JavaScript files, that are referenced in the HTML. A solution could be, to write all the CSS and JS inline (e.g. by using a build process).

like image 130
Rias Avatar answered Sep 20 '22 01:09

Rias


I was able to include html5/javascript into project by using { html: , baseUrl: } as source. But to be frank, it's more like a lucky shot.

<WebView source={{ html: HTML, baseUrl: 'web/' }} />

I have index.html, which require pano2vr_player.js and pano.xml to make this code work.

const HTML = `
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<title></title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0" />
		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black" />
		<meta name="mobile-web-app-capable" content="yes" />
		<style type="text/css" title="Default">
			body, div, h1, h2, h3, span, p {
				font-family: Verdana,Arial,Helvetica,sans-serif;
			}
    </style>
	</head>
	<body>
		<script type="text/javascript" src="pano2vr_player.js">
		</script>
		<div id="container" style="width:100%;height:100%;">
		<br>Loading...<br><br>
		This content requires HTML5 with CSS3 3D Transforms or WebGL.
    </div>
		<script type="text/javascript">
			// create the panorama player with the container
			pano=new pano2vrPlayer("container");
		  window.addEventListener("load", function() {
			  pano.readConfigUrlAsync("pano.xml");
		  });
		</script>
	</body>
</html>`;

class PanoView extends Component {

  render() {
    return (
      <View>
        <WebView
          style={{ flex: 1, width: 1024, height: 768 }}
          source={{ html: HTML, baseUrl: 'web/' }}
          javaScriptEnabledAndroid={true} />
      </View>
    );
  }
}

And finally add files/folder ('/web' same as baseUrl) to XCode project

enter image description here

And it works! But I'm not sure how...

like image 30
Doppio Avatar answered Sep 20 '22 01:09

Doppio