Issue
In my Xamarin App I am using a WebView to retrieve data from a service. The information is stored in the meta-tag of the head of the HTML.
In Xamarin.iOS I could manage to access this information with this code:
webView.LoadFinished += async (sender, args) => {
var request = webView.Request;
if (request != null) {
var url = request.Url.AbsoluteString;
var data = NSData.FromUrl(NSUrl.FromString(Url));
var content = data.ToString();
var splits = content.Split("<meta").ToList();
var taggedSplit = splits.Find(x => x.Contains("myTag"));
if (!string.IsNullOrEmpty(taggedSplit)) {
// do stuff
}
}
}
But i can't find a working solution for Xamarin.Android. I tried this (Access the http response headers in a WebView) approach without success.
Maybe you can help me with this problem.
Solution
you could get the value by inject a section of js code,here is a simple sample,you could check it.
in the activity :
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_other);
webView = FindViewById<WebView>(Resource.Id.webView1);
webView.SetWebViewClient(new WebViewClientClass());
WebSettings websettings = webView.Settings;
websettings.JavaScriptEnabled = true;
websettings.DomStorageEnabled = true;
webView.AddJavascriptInterface(new Foo(this), "Foo");
webView.LoadUrl("file:///android_asset/demo.html");
}
class WebViewClientClass : WebViewClient
{
public override void OnPageFinished(WebView view, string url)
{
//access to parse < meta name = "viewport" content = "get the value of content" >
view.LoadUrl("javascript:window.Foo.showSource("
+ "document.querySelector('meta[name=\"viewport\"]').getAttribute('content')"
+ ");");
base.OnPageFinished(view, url);
}
}
class Foo : Java.Lang.Object
{
Context context;
public Foo(Context context)
{
this.context = context;
}
[JavascriptInterface]
[Export]
public void showSource(string source)
{
// here you could get the value of meta content
// in this example,i could get source = "width =device-width,initial-scale=1, maximum-scale=1"
Log.Error("content", html);
}
}
the local html :
<html>
<head>
<meta name="viewport" content="width =device-width,initial-scale=1, maximum-scale=1">
</head>
<body>
...
</body>
</html>
Answered By - Leo Zhu - MSFT
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.