Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load local image file from within WebView

I have a React Native WebView that runs a small HTML document. The document shows a few images.

My hope is to show images located in the app's Documents folder, i.e. the images are not static assets, but are downloaded by the app at runtime and stored on disk. These images are then referenced from HTML running inside a React Native WebView.

This is what I have tried so far:

Sourcing the file directly

I have tried sourcing the file from within the WebView which does not work (404 Not Found):

1. Simulator

::1 - - [25/Nov/2016:09:55:52 +0000] "GET /Users/me/Library/Developer/CoreSimulator/Devices/43707753-69A2-4EC7-B990-F7910A853F42/data/Containers/Data/Application/E4F4A368-02B0-4BAE-BEB3-BDF0FF7ADDDF/Documents/1657.jpeg HTTP/1.1" 404 193 "http://localhost:8081/assets/src/index.html?platform=ios&hash=8cb6d49177b95c46ed6654eb038a9a8d" "Mozilla/5.0 (iPhone; CPU iPhone OS 10_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/14B72"

2. Phone

::ffff:192.168.100.143 - - [25/Nov/2016:11:58:31 +0000] "GET /var/mobile/Containers/Data/Application/970B3033-4AB1-48CF-AFC9-D30534D30BCE/Documents/1657.jpeg HTTP/1.1" 404 108 "http://192.168.100.114.xip.io:8081/assets/src/index.html?platform=ios&hash=8cb6d49177b95c46ed6654eb038a9a8d" "Mozilla/5.0 (iPhone; CPU iPhone OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/14B100"

Seeing as I think this is the correct path (for iOS at least), I think it might be a permissions problem, although unsure.

like image 441
plougsgaard Avatar asked Nov 25 '16 11:11

plougsgaard


1 Answers

Looking at the docs for React Native WebView component, the source property has two modes:

  1. Load a URI
  2. Load a static HTML string
  3. The result of a call to require(some.html)

In the second case it is possible to specify a baseUrl. If you set the baseUrl to the directory into which images are downloaded, you should be able to reference them by using <img src="./your-image.png" />.

Post-answer edit: Clarification regarding external HTML

Sadly there is no way to specify a base URL in cases 1 and 3, so you have to first convert it to a string which can be passed to the source property. If your HTML refers some external Javascript, you have to get a reference to the bundle directory path, which is where those files have to be to be readable by your app, and reference them relative to that path.

EDIT: This refers to React Native 0.38

like image 80
mdiin Avatar answered Oct 17 '22 15:10

mdiin