2

I've seen multiple tutorials adding a GetBaseUrl separately for IOS and Android, but they don't answer my question. I was wondering if there is no other way to add custom CSS to a webview and only use 1 stylesheet (default.css). The reason why I want to do this is because my stylesheet is identical for both IOS and Android and contains little styling.

This is what I've tried: I have a WebView:

 <WebView.Source >
        <HtmlWebViewSource Html="{Binding Data.Content}" />
    </WebView.Source>

The Source of this WebView is a string that looks like this:

string  contentString =   @"<html>
                            <head>" +
                            "<link rel='stylesheet' href='default.css'" 
                            "</head>" +
                            "<body style='text-align:left;background-color:white;font-size:16px;margin:0;'>" +
                            value +
                            "</body>" +
                            "</html>";

The default.css file mentioned above is in my Assets folder and has Build Action EmbeddedResource, located in the root directory of my project:

e

Can anyone help? Thanks in advance.

IT-Girl
  • 448
  • 5
  • 24
  • Since it is an assembly-based embedded resource, read it out of the assembly as a string and inline it into your html in-between a ` – SushiHangover May 27 '19 at 20:01
  • Hello, thank you for your answer. I do not know how to do this. Can you give me a hint? – IT-Girl May 27 '19 at 21:48

2 Answers2

2

There are some ways to do this, one is to use HtmlWebViewSource, the html is like this:

htmlSource.Html = @"<html>
<head>
<link rel=""stylesheet"" href=""default.css"">
</head>
<body>
<h1>Xamarin.Forms</h1>
<p>The CSS and image are loaded from local files!</p>
<img src='XamarinLogo.png'/>
<p><a href=""local.html"">next page</a></p>
</body>
</html>";

Another way is to use WebView.loadDataWithBaseURL, there is the same thread that you can take a look:

Rendering HTML in a WebView with custom CSS

Cherry Bu - MSFT
  • 10,160
  • 1
  • 10
  • 16
1

The easiest way is to wrap your HTML with CSS (or replace link tags with its resulting content)

var html = AddHtmlAndCssTags("<div>my html</div>", ReadCss());





protected string ReadCss()
{
    var resourceName = $"MyProj.Resources.Css.article.css";
    var isExists = ResourceLoader.IsEmbeddedResourceExists(Assembly.GetAssembly(typeof(ResourceLoader)), resourceName);

    if (isExists)
    {
        return ResourceLoader.GetEmbeddedResourceString(Assembly.GetAssembly(typeof(ResourceLoader)), resourceName);
    }

        return string.Empty;
    }

    protected string AddHtmlAndCssTags(string html, string css)
    {
        var cssTag = string.IsNullOrEmpty(css) ? string.Empty : $"<style>{css}</style>";
        return $"<html><head>{cssTag}</head><body>{html}<body></html>";
    }
Pavlo Datsiuk
  • 1,024
  • 9
  • 17