Home > Mobile >  Passing a query string to HtmlWebViewSource - Xamarin.Forms
Passing a query string to HtmlWebViewSource - Xamarin.Forms

Time:02-25

I have the following code used in a Xamarin.Forms project:

var htmlSource = new HtmlWebViewSource { Html = @"<html>
                                                      <head>
                                                         <script async src=""https://URL""></script>
                                                      </head>
                                                      <body>
                                                          <div class-name""></div>
                                                       </body>
                                                  </html>" };
 myWebView.Source = htmlSource;

Is it possible to define a query parameter - lets say q - and pass a variable with a query string to the HTML code, before loading it in the WebView?

CodePudding user response:

You could use string interpolation to inject the value in the object initializer:

// query
var q = 123;
// url with query
var url = $"https://www.somesite.com?q={q}";
var htmlSource = new HtmlWebViewSource 
{ 
    Html = @$"<html>
                  <head>
                     <script async src=""{url}""></script>
                  </head>
                  <body>
                      <div class-name""></div>
                   </body>
              </html>"
};

Output of htmlSource.Html:

<html>
      <head>
         <script async src="https://www.somesite.com?q=123"></script>
      </head>
      <body>
          <div ></div>
       </body>
  </html>

CodePudding user response:

You can use Customizing a WebView.

First you can create a custom renderer.

Then implement it on different platforms.

Finally, you can call and pass parameters.

For how to use it, please refer to: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview#create-the-hybridwebview.

  • Related