I'm using Xamarin forms WebView control to display a page that uses Authentication JWT token. I could not find any samples that does this either in Microsoft site or any blogs.
Most closest answer I found is to create a renderer for the control in each platform (iOS and Droid). But I'm not sure on which event I should override the request and the format in which the auth header can be passed. Appreciate any help.
You could try the method below:
For Android:
public class FormsWebViewRenderer : ViewRenderer<Xamarin.Forms.WebView, Android.Webkit.WebView>
{
Android.Content.Context _localContext;
public FormsWebViewRenderer(Context context) : base(context)
{
_localContext = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
Dictionary<string, string> headers = new Dictionary<string, string>
{
["A-custom-header"] = "a custom value"
};
Android.Webkit.WebView webView = Control as Android.Webkit.WebView;
if (Control == null) {
webView = new Android.Webkit.WebView(_localContext);
SetNativeControl(webView);
}
webView.Settings.JavaScriptEnabled = true;
webView.Settings.BuiltInZoomControls = true;
webView.Settings.SetSupportZoom(true);
webView.ScrollBarStyle = ScrollbarStyles.OutsideOverlay;
webView.ScrollbarFadingEnabled = false;
webView.SetWebViewClient(new FormsWebViewClient(headers));
UrlWebViewSource source = Element.Source as UrlWebViewSource;
webView.LoadUrl(source.Url, headers);
}
}
public class FormsWebViewClient : Android.Webkit.WebViewClient
{
public Dictionary<string, string> headers { get; set; }
public FormsWebViewClient(Dictionary<string, string> requestHeaders)
{
headers = requestHeaders;
}
public override void OnPageStarted(Android.Webkit.WebView view, string url, Android.Graphics.Bitmap favicon)
{
base.OnPageStarted(view, url, favicon);
System.Diagnostics.Debug.WriteLine("Loading website...");
}
public override void OnPageFinished(Android.Webkit.WebView view, string url)
{
base.OnPageFinished(view, url);
System.Diagnostics.Debug.WriteLine("Load finished.");
}
public override void OnReceivedError(Android.Webkit.WebView view, IWebResourceRequest request, WebResourceError error)
{
base.OnReceivedError(view, request, error);
}
}
For ios:
public class FormsWebViewRenderer : ViewRenderer<WebView, UIWebView>
{
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
var webView = Control as UIWebView;
if (webView == null) {
webView = new UIWebView();
SetNativeControl(webView);
}
webView.ScalesPageToFit = true;
webView.LoadStarted += (object sender, System.EventArgs evtArgs) => {
System.Diagnostics.Debug.WriteLine("Loading...");
};
webView.LoadFinished += (object sender, System.EventArgs evtArgs) => {
System.Diagnostics.Debug.WriteLine("Load finished.");
};
if (e.NewElement != null) {
UrlWebViewSource source = (Xamarin.Forms.UrlWebViewSource)Element.Source;
var webRequest = new NSMutableUrlRequest(new NSUrl(source.Url));
var headerKey = new NSString("A-custom-header");
var headerValue = new NSString("a custom value");
var dictionary = new NSDictionary(headerKey, headerValue);
webRequest.Headers = dictionary;
this.Control.LoadRequest(webRequest);
}
}
}
Related
I'm using a webview in my Xamarin Forms project with Hybrid Renderer and webview, because I have to inject javascript code inside the page.
In my main project I have a CustomWebview.cs:
namespace ClotureSiadForms.Renderer
{
public class CustomWebView : WebView
{
public string js = "";
public CustomWebView()
{
Navigating+= WebViewNavigating;
Navigated+=WebViewNavigated;
}
private void WebViewNavigated(object sender, WebNavigatedEventArgs args)
{
EvaluateJavaScriptAsync(js);
}
public void WebViewNavigating(object sender, WebNavigatingEventArgs args)
{
if (args.Url.StartsWith("tel:"))
{
var tel = args.Url.Split(':')[1];
args.Cancel = true;
Xamarin.Essentials.PhoneDialer.Open(tel);
}
else if (!args.Url.StartsWith("http") || args.Url.EndsWith(".apk") || args.Url.EndsWith(".pdf") || args.Url.EndsWith(".zip"))
{
args.Cancel = true;
Xamarin.Essentials.Launcher.OpenAsync(args.Url);
}
}
}
}
In my Android project I have a HybridWebViewRenderer.cs:
[assembly: ExportRenderer(typeof(CustomWebView), typeof(HybridWebViewRenderer))]
namespace ClotureSiadForms.Droid.Renderer
{
internal class HybridWebViewRenderer : WebViewRenderer
{
public HybridWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
CustomWebView webview = e.NewElement as CustomWebView;
Control.Settings.JavaScriptEnabled = true;
Control.Settings.DomStorageEnabled = true;
Control.Settings.SavePassword = true;
}
}
}
}
As is, it worked and was able to download files
But as I needed basic authentication, I added a custom webviewclient inside HybridWebViewRenderer.cs:
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
CustomWebView webview = e.NewElement as CustomWebView;
Control.Settings.JavaScriptEnabled = true;
Control.Settings.DomStorageEnabled = true;
Control.Settings.SavePassword = true;
var login = Preferences.Get("login", "");
var password = Preferences.Get("password", "");
Control.SetWebViewClient(new AuthWebViewClient(login, password));
}
}
public class AuthWebViewClient : WebViewClient
{
private string Username;
private string Password;
public AuthWebViewClient(string username, string password)
{
Username = username;
Password = password;
}
public override void OnReceivedHttpAuthRequest(Android.Webkit.WebView view, HttpAuthHandler handler, string host, string realm)
{
handler.Proceed( Username,Password);
}
}
And authentication works, but WebViewNavigating is now called once, then the custom client is set and then WebViewNavigating is never more called.
Then my question is, can't I use basic auth without a custom client or is there a way to keep using my customwebview with the client ?
And authentication works, but WebViewNavigating is now called once, then the custom client is set and then WebViewNavigating is never more called.
I tested the code you provided and added Breakpoint to WebViewNavigating method. Even if you do not add webviewclient, it will only call WebViewNavigating once.
You can put the code in WebViewNavigating to ShouldInterceptRequest:
public class AuthWebViewClient : WebViewClient
{
...
public override WebResourceResponse ShouldInterceptRequest(Android.Webkit.WebView view, IWebResourceRequest request)
{
var url = request.Url;
...
}
}
Whenever the WebView begins loading a new page, it will call ShouldInterceptRequest.
I have implemented WebViewRenderer it works well on Android but it doesn't work on iOS. It displays the value, but then user clicks next button and the value doesn't update. I have tried the the example on ms website, but that displayed no text, I don't have the values from URL. I have also tried several post here.
[assembly: ExportRenderer(typeof(ExtendedWebView), typeof(ExtendedWebViewRenderer))]
namespace MyApp.iOS.Renderers
{
public class ExtendedWebViewRenderer : ViewRenderer<ExtendedWebView, WKWebView>
{
WKWebView _wkWebView;
static ExtendedWebView _xwebView = null;
protected override void OnElementChanged(ElementChangedEventArgs<ExtendedWebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
WKWebViewConfiguration config = new WKWebViewConfiguration();
_wkWebView = new WKWebView(Frame, config);
_wkWebView.NavigationDelegate = new CustomWKNavigationDelegate(this);
SetNativeControl(_wkWebView);
}
if (e.NewElement != null)
{
HtmlWebViewSource source = (Xamarin.Forms.HtmlWebViewSource)Element.Source;
string html = source.Html;
_wkWebView.LoadHtmlString(html, baseUrl: null);
_wkWebView.ScrollView.ScrollEnabled = false;
_wkWebView.SizeToFit();
}
}
}
public class CustomWKNavigationDelegate : WKNavigationDelegate
{
ExtendedWebViewRenderer _webViewRenderer;
public CustomWKNavigationDelegate(ExtendedWebViewRenderer webViewRenderer)
{
_webViewRenderer = webViewRenderer;
}
public override async void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{
var wv = _webViewRenderer.Element as ExtendedWebView;
if (wv != null)
{
await System.Threading.Tasks.Task.Delay(100); // wait here till content is rendered
wv.HeightRequest = (double)webView.ScrollView.ContentSize.Height;
}
}
}
}
[assembly: ExportRenderer(typeof(ExtendedWebView), typeof(ExtendedWebViewRenderer))]
namespace MyApp.Droid.Renderers
{
public class ExtendedWebViewRenderer : WebViewRenderer
{
public static int _webViewHeight;
static ExtendedWebView _xwebView = null;
public WebView _webView;
bool isScroll;
[Obsolete]
public ExtendedWebViewRenderer(Context context) : base(context)
{
}
class ExtendedWebViewClient : WebViewClient
{
WebView _webView;
public async override void OnPageFinished(WebView view, string url)
{
try
{
_webView = view;
if (_xwebView != null)
{
view.Settings.JavaScriptEnabled = true;
await Task.Delay(100);
string result = await _xwebView.EvaluateJavaScriptAsync("(function(){return document.body.scrollHeight;})()");
_xwebView.HeightRequest = Convert.ToDouble(result);
}
base.OnPageFinished(view, url);
}
catch (Exception ex)
{
Console.WriteLine($"{ex.Message}");
}
}
public override bool ShouldOverrideUrlLoading(Android.Webkit.WebView view, IWebResourceRequest request)
{
return true;
}
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
_xwebView = e.NewElement as ExtendedWebView;
_webView = Control;
if (e.OldElement == null)
{
_webView.SetWebViewClient(new ExtendedWebViewClient());
}
}
}
}
public class ExtendedWebView : WebView
{
public ExtendedWebView()
{
}
}
XAML
<controls:ExtendedWebView
VerticalOptions="FillAndExpand" Grid.RowSpan="2"
x:Name="enView"
Opacity="1"
Source="{Binding CZ, Mode=TwoWay}"/>
private static HtmlWebViewSource htmlSourceExplanation = new HtmlWebViewSource();
public HtmlWebViewSource Cz
{
get { return _cz; }
set
{
_cz = value;
NotifyPropertyChanged(nameof(Cz));
}
}
private void SetExplanationDetail(string text, string text2)
{
htmlSourceExplanation.Html = _style + "<div class=\"text\"><div>" + text + "</div><div>" + text2 + "</div></div>";
_cz = htmlSourceExplanation;
NotifyPropertyChanged("Cz");
}
I expect the value to change once to user cliks the button. `
I have implemented a custom web view renderer in Droid project.
How can I redirect the Phone Dialer from WebView when I click on a phone number in WebView?
Any help is appreciated. Thanks!
You can try the following code:
public class MyWebViewRenderer : WebViewRenderer
{
public MyWebViewRenderer(Context context) : base(context) { }
static MyWebView _xwebView = null;
WebView _webView;
class ExtendedWebViewClient : Android.Webkit.WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
var tel = "tel:";
if (url != null)
{
if (url.StartsWith(tel))
{
var uri = Android.Net.Uri.Parse(url);
var intent = new Intent(Intent.ActionView, uri);
intent.SetFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
return true;
}
}
return false;
}
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
_xwebView = e.NewElement as MyWebView;
_webView = Control;
if (e.OldElement == null)
{
_webView.SetWebViewClient(new ExtendedWebViewClient());
}
}
}
And for the ios part:
public class MyWebViewRenderer : WkWebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
NavigationDelegate = new MyWKNavigationDelegate();
}
class MyWKNavigationDelegate : WKNavigationDelegate
{
[Export("webView:decidePolicyForNavigationAction:decisionHandler:")]
public override void DecidePolicy(WKWebView webView, WKNavigationAction
navigationAction, Action<WKNavigationActionPolicy> decisionHandler)
{
var navType = navigationAction.NavigationType;
var targetFrame = navigationAction.TargetFrame;
var url = navigationAction.Request.Url;
if (
url.ToString().StartsWith("http") && (targetFrame != null &&
targetFrame.MainFrame == true)
)
{
decisionHandler(WKNavigationActionPolicy.Allow);
}
else if (
url.ToString().StartsWith("mailto:")
|| url.ToString().StartsWith("tel:")
|| url.ToString().StartsWith("Tel:"))
{
UIApplication.SharedApplication.application.OpenUrl(url);
}
}
}
}
This seems like a simple thing - I want to use a WebView to load / run some JavaScript from a 3rd party.
When I load the page I get a message saying "You must allow popups for this to work". I think I need to create a custom WebView (for iOS and Android!?) and I assume I need one in the shared project too?
I added this to my Android project:
using Android.Content;
using MyApp.Custom;
using MyApp.Droid.Custom;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace MyApp.Droid.Custom
{
public class CustomWebViewRenderer : WebViewRenderer
{
public CustomWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
Control.Settings.JavaScriptCanOpenWindowsAutomatically = true;
Control.Settings.JavaScriptEnabled = true;
}
}
}
and this to my shared project
using Xamarin.Forms;
namespace MyKRing.Custom
{
public class CustomWebView : WebView
{
}
}
and then used "CustomWebView" in my XAML.
<custom:CustomWebView x:Name="WebView"
HeightRequest="1000"
Source="{Binding WebViewContent}"
WidthRequest="1000" />
My TestPageViewModel has
public WebViewSource WebViewContent
{
get => _webViewContent;
set => SetProperty(ref _webViewContent, value);
}
public TestPageViewModel()
{
AmountEntryFrameVisible = true;
NuapayFrameVisible = false;
ConfirmLoadCommand = new Command(ExecuteConfirmLoadCommand);
var localHtml = new HtmlWebViewSource();
localHtml.Html = #"<html>
<body>
<p>This is a test</p>
<script src='https://testurl.com/test.js\'></script>
<script>
TestJS.showUI('1234567890', 'https://testurl.com/ui/');
</script>
</body>
</html>";
WebViewContent = localHtml;
}
With the aim of making the JS run when the page is loaded by WebView.
Am I anywhere close? What is wrong with the above, as it just doesn't do anything (that ( can see).
1. Create the CustomWebView and create the ShowDialog method.
public class CustomWebView : WebView
{
Action<string> action;
public static readonly BindableProperty UriProperty = BindableProperty.Create(
propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(CustomWebView ),
defaultValue: default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
public void RegisterAction(Action<string> callback)
{
action = callback;
}
public void Cleanup()
{
action = null;
}
public void ShowDialog(string data)
{
if (action == null || data == null)
{
return;
}
action.Invoke(data);
}
}
2. Consume the CustomWebView
<local:CustomWebView x:Name="customWebView " Uri="index.html" />
3. Register the ShowDiaplg action to be invoked from JavaScript
customWebView.RegisterAction(data => DisplayAlert("Alert", DateTime.Now + "/n" + data, "OK"));
4. Create the custom renderer on Android platform.
CustomWebViewRenderer .cs:
[assembly: ExportRenderer(typeof(CustomWebView ), typeof(CustomWebViewRenderer))]
namespace CustomRenderer.Droid
{
public class CustomWebViewRenderer: WebViewRenderer
{
const string JavascriptFunction = "function invokeCSharpAction(data){jsBridge2.showDialog(data);}";
Context _context;
public CustomWebViewRenderer (Context context) : base(context)
{
_context = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
Control.RemoveJavascriptInterface("jsBridge");
((CustomWebView )Element).Cleanup();
}
if (e.NewElement != null)
{
Control.SetWebViewClient(new JavascriptWebViewClient2(this, $"javascript: {JavascriptFunction}"));
Control.AddJavascriptInterface(new JSBridge2(this), "jsBridge2");
Control.LoadUrl($"file:///android_asset/Content/{((CustomWebView )Element).Uri}");
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((CustomWebView )Element).Cleanup();
}
base.Dispose(disposing);
}
}
}
JavascriptWebViewClient2.cs:
public class JavascriptWebViewClient2 : FormsWebViewClient
{
string _javascript;
public JavascriptWebViewClient2(CustomWebViewRenderer renderer, string javascript) : base(renderer)
{
_javascript = javascript;
}
public override void OnPageFinished(WebView view, string url)
{
base.OnPageFinished(view, url);
view.EvaluateJavascript(_javascript, null);
}
}
JSBridge2.cs:
public class JSBridge2 : Java.Lang.Object
{
readonly WeakReference<CustomWebViewRenderer > hybridWebViewRenderer;
public JSBridge2(CustomWebViewRenderer hybridRenderer)
{
hybridWebViewRenderer = new WeakReference<CustomWebViewRenderer >(hybridRenderer);
}
[JavascriptInterface]
[Export("showDialog")]
public void ShowDialog(string data)
{
CustomWebViewRenderer hybridRenderer;
if (hybridWebViewRenderer != null && hybridWebViewRenderer.TryGetTarget(out hybridRenderer))
{
((CustomWebView)hybridRenderer.Element).ShowDialog(data);
}
//string ret = "Alert :" + DateTime.Now;
//return ret;
}
}
I followed the code sample in the link below. https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/customrenderers-hybridwebview/
I'm trying to make async call with WSDL that belongs to SIRI (SIRI
Service Interface for Real Time Information), How can I "catch" the response if I call "GetStopMonitoringServiceAsync" ?
Relevant part from the WSDL:
public void GetStopMonitoringServiceAsync(ServiceRequestStructure Request) {
this.GetStopMonitoringServiceAsync(Request, null);
}
/// <remarks/>
public void GetStopMonitoringServiceAsync(ServiceRequestStructure Request, object userState) {
if ((this.GetStopMonitoringServiceOperationCompleted == null)) {
this.GetStopMonitoringServiceOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetStopMonitoringServiceOperationCompleted);
}
this.InvokeAsync("GetStopMonitoringService", new object[] {
Request}, this.GetStopMonitoringServiceOperationCompleted, userState);
}
private void OnGetStopMonitoringServiceOperationCompleted(object arg) {
if ((this.GetStopMonitoringServiceCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetStopMonitoringServiceCompleted(this, new GetStopMonitoringServiceCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
public new void CancelAsync(object userState) {
base.CancelAsync(userState);
}
Managed..
SS.GetStopMonitoringServiceCompleted += new GetStopMonitoringServiceCompletedEventHandler(GetStopMonitoringServiceCompletedEventHandler);
static void GetStopMonitoringServiceCompletedEventHandler(object sender, GetStopMonitoringServiceCompletedEventArgs e)
{
ServiceDeliveryStructure Response = new ServiceDeliveryStructure();
Response = e.Result;
}