如何从 xamarin android web 视图中加载的登录页面的用户名文本框中读取值

问题描述 投票:0回答:2

用户在 Xamarin android 中使用 webview 在网页中输入用户名文本框中的值后,我尝试从登录页面获取用户名文本框中的值。

我尝试使用“document.getelementbyid('useranme').values”

但它总是返回空值。有人可以帮忙吗?

xamarin xamarin.android android-webview
2个回答
0
投票

最终我找到了解决我的问题的方法。

我在 webview 中有用户 OnLoadResource 函数,它帮助我获取我正在搜索的数据

public override void OnLoadResource(WebView view, string url)
{
    try
    {
        view.EvaluateJavascript("document.getElementById('username').value;", this);

    }
    catch (Java.Lang.Exception oe)
    {

    }
    base.OnLoadResource(view, url);
}

谢谢。


0
投票

可以在C#中使用JS调用方法。

例如,我在assets文件夹中创建login.html:

<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="lolkittens" />
<script charset="utf-8" type="text/javascript">
    function check() {
        var username = document.getElementById("ID").value;
        var password = document.getElementById("Pass").value;
        alert("Username: " + username + "  Password: " + password);

        return CSharp.ShowToast(username);
    }
 
</script>
<title>Untitled 1</title>
<div id="main" style="width: 300px; height: 200px;">
    <form name="MainForm" id="MainForm">
        <input id="ID" name="ID" type="text" size="20" />
        <input id="Pass" name="Pass" type="password" size="20" />
    </form>
    <button value="click Me" onclick="check()"> Click Me </button>
</div>

在 Mainactivity.cs 中,

 public class MainActivity : AppCompatActivity
{

    private WebView webview;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.activity_main);

        webview = FindViewById<WebView>(Resource.Id.webview);
        WebSettings settings = webview.Settings;
        settings.JavaScriptEnabled = true;
        // load the javascript interface method to call the foreground method
        webview.AddJavascriptInterface(new MyJSInterface(this), "CSharp");
        webview.SetWebViewClient(new WebViewClient());
        //webview.EvaluateJavascript("javascript: check();", new EvaluateBack());

        webview.LoadUrl("file:///android_asset/login.html");
    }
}

创建要返回值的 C# 类。

class MyJSInterface : Java.Lang.Object
{
    Context context;

    public MyJSInterface(Context context)
    {
        this.context = context;
    }

    [JavascriptInterface]
    [Export]
    public void ShowToast(string msg)
    {
        Toast.MakeText(context, msg, ToastLength.Short).Show();
    }
}

请不要忘记在您的引用中添加 Mono.Android.Export.dll。

更多关于调用C#方法,请看:

https://github.com/xamarin/docs-archive/tree/master/Recipes/android/controls/webview/call_csharp_from_javascript

© www.soinside.com 2019 - 2024. All rights reserved.