Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which base url should I give a WebView in order for WebView to correctly load css and font files?

In my Native React project I want to use a WebView. The HTML refers to an external css file and the css file refers to some custom fonts.

Given this hierarki:

app/
app/index.ios.js
app/android.ios.js
app/package.json
app/node_modules
app/android/
app/ios/

where should I put the files "mycss.css" and the "fonts/" folder and what whould I use for the baseUrl ? Do the package manager automatically include css and font files, when building the ios and android builds?

    <WebView style={{flex: 1}}
             source={ { html:    my_html, 
                        baseUrl: ???} } />

Examining the code behind WebView on iOS shows that baseUrl is handed to a UIWebView. This StackOverFlow question How can I add an external stylesheet to a UIWebView in Xcode? shows how to set the baseUrl from Objective C, but what is the equivalent in Native React?

NSURL *mainBundleURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[self.webView loadHTMLString:htmlString baseURL:mainBundleURL];

FWIW I am developing on iOS (but hopefully there is a way to make this work on both platforms).

like image 929
soegaard Avatar asked Nov 28 '25 15:11

soegaard


1 Answers

The following worked.

Added a folder web and used this structure:

app/web/mycss.css
app/web/fonts

Used web/ as base url.

The final piece of the puzzle is to add the web folder to the XCode project (do this in XCode). Otherwise the files in the web folder are not included in the bundle built for the ios device.

like image 87
soegaard Avatar answered Dec 01 '25 05:12

soegaard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!