2

I'm able to load a local HTML file into my WebView like this (this works fine):

var fileName = "Views/Default.html"; 
var localHtmlUrl = Path.Combine(NSBundle.MainBundle.BundlePath, fileName);
var url = new NSUrl(localHtmlUrl, false);
var request = new NSUrlRequest(url);
WebView.LoadRequest(request);

I'd like to reference a CSS file (also local) in my HTML file:

<link href="Content/style.css" rel="stylesheet">

The CSS file does exist inside of a Content folder, the build action is set to Content for said file.

How can I reference/load the CSS file in question via my html file? Possible?

UPDATE: Had css and html in separate folders. Put them both in a Content folder then updated the hrefs which solved the issue while using LoadRequest.

1 Answer 1

3

Check this link https://developer.xamarin.com/recipes/ios/content_controls/web_view/load_local_content/

Section Additional information

Html generated in code can also be displayed, which is useful for customizing the content. To display an Html string, use the LoadHtmlString method instead of LoadRequest. Passing the path to the Content directory helps the web view resolve relative Urls in the Html, such as links, images, CSS, etc.

// assumes you've placed all your files in a Content folder inside your app
string contentDirectoryPath = Path.Combine (NSBundle.MainBundle.BundlePath, "Content/");
string html = "<html><a href='Home.html'>Click me</a></html>";
webView.LoadHtmlString(html, new NSUrl(contentDirectoryPath, true));
Sign up to request clarification or add additional context in comments.

3 Comments

Correct answer, but better if you copy-paste the code here in case the link becomes broken in the future
I've seen this, but LoadHtmlString takes a string. Do I have to read all my html files as a string just for the that method? Honestly, seems like I am missing something.
I think you can load only one html at once. So I don't see a big problem to read it before you set source of webview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.