Forum Xamarin.Forms

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

How to reference downloaded assets within a WebView in a shared PCL Project

I am downloading a zip file from our server which contains html files, images, css etc. unzipping the files and saving them within the PCL using PCLStorage nuget package.
To view the content I am using a WebView to display the html that has been loaded successfully via reading in a stream and converting to byteArray to get at the HTML.
The problem is that relative references to images, css & js do not work even when setting the baseUrl for the HtmlSource using a dependency service as suggested in other support topics. (tested on Android and iOS simulators)
How can I load these downloaded assets in the WebView?

Best Answer

  • GurpalVirdee.5730GurpalVirdee.5730 USMember ✭✭
    Accepted Answer

    I have solved this issue

    Set base url for app based on OS:
    case Device.iOS:
    webContentBaseUrl = FileSystem.AppDataDirectory + "/";
    break;
    case Device.Android:
    webContentBaseUrl = @"file://" + FileSystem.AppDataDirectory + "/";
    break;

    Create your HtmlSource passing in the baseURL:

    HtmlSource = new HtmlWebViewSource { Html = myHtmlString, BaseUrl = webContentBaseUrl };

    Reference the css/js/images using relative paths within your html that is being rendered by the WebView:

    <link rel=""stylesheet"" type=""text/css"" href=""global/guide.css""></link>

    "global" is a folder I have created within the AppDataDirectory, that contains my downloaded css file, "guide.css"

Answers

  • KenBrowerKenBrower USMember

    Anyone find an answer for this? We have the same issue and cannot figure out how to use files stored under the PCLStorage.FileSystem folders in a WebView. Looking for a solution that works for iOS, Andriod and Windows UWP.

  • Anybody?

  • GurpalVirdee.5730GurpalVirdee.5730 USMember ✭✭
    Accepted Answer

    I have solved this issue

    Set base url for app based on OS:
    case Device.iOS:
    webContentBaseUrl = FileSystem.AppDataDirectory + "/";
    break;
    case Device.Android:
    webContentBaseUrl = @"file://" + FileSystem.AppDataDirectory + "/";
    break;

    Create your HtmlSource passing in the baseURL:

    HtmlSource = new HtmlWebViewSource { Html = myHtmlString, BaseUrl = webContentBaseUrl };

    Reference the css/js/images using relative paths within your html that is being rendered by the WebView:

    <link rel=""stylesheet"" type=""text/css"" href=""global/guide.css""></link>

    "global" is a folder I have created within the AppDataDirectory, that contains my downloaded css file, "guide.css"

Sign In or Register to comment.