Loading dynamic html and javascript from assets in a WebView

IanVinkIanVink CAInsider, University ✭✭✭

I am trying to display my domain object in a webview. The UI is simple jQuery Mobile. The HTML displays, but the CSS and javascript from the assets folder does not.

I create the WebView like this:

        WebView webView = FindViewById<WebView>(Resource.Id.EntityWebView);
        webView.Settings.JavaScriptEnabled = true;
        webView.SetWebChromeClient(new WebChromeClient());
        webView.Settings.DomStorageEnabled = true;
        webView.LoadData(getMy.Html(), "text/html", "UTF-8");

My html, that is created on the fly is displayed, but the CSS and JS from jQuery is not. I reference it like this:

<meta name='viewport' content='width=device-width, initial-scale=1'> 
<link rel='stylesheet' href='file:///android_asset/html/jquery.mobile.css' />
<script src='file:///android_asset/html/jquery.js' type='text/javascript'></script>
<script src='file:///android_asset/html/jquery.mobile.js' type='text/javascript'></script>

The files are markets as AndroidAssets


  • evalinaevalina USMember

    very good solution.

    webView.LoadDataWithBaseURL("file:///android_asset/",somehtml, "text/html", "UTF-8",null);

    but what is the somehtml.it seems a string parameter. It's a html-file? if so,how to load it on WebView?

  • RamsCHOARamsCHOA USMember

    Here is a trick I tried that seems to work. The advantage is you don't have to load the massive string that represents your html files.

    var html = @"<html><head><script type='text/javascript'>window.location.replace('file:///android_assets/<folder>/index.html')</script></head><body></body></html>"
    webView.LoadDataWithBaseURL("file///android_asset/", html, "text/html", "UTF-8", null);

    You can format the html string to navigate as needed.

Sign In or Register to comment.