Activity中Webview的Html按钮点击检测(java代码)

Posted

技术标签:

【中文标题】Activity中Webview的Html按钮点击检测(java代码)【英文标题】:Webview's Html button click detection in Activity(java code) 【发布时间】:2014-01-21 22:11:46 【问题描述】:

我试图检测 webview 的 html 按钮点击进入 java 代码(在活动中)。 我推荐了另一个 SODetect click on HTML button through javascript in android WebView

但不工作。我的代码:

index.html

<html>
    <head>
        <script language="javascript">
            function js1() 
                document.loginform.method="post";
                document.loginform.action = "https://example.com/chechlogin.asp";
            
        </script>  
    </head>
    <body>
        <form name="loginform">
            <input type="text" name="empcode" value="58686" /><br/>
            <input type="password" name="emppassNTL" />
            <input type="submit" name="submit" id="submit_id" onclick="login.performClick();" />    
        </form>
    </body>
</html>

MainActivity.java

package com.example.webview;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity 

   private EditText field;
   private WebView browser;

   @Override        
   protected void onCreate(Bundle savedInstanceState) 
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      field = (EditText)findViewById(R.id.urlField);
      browser = (WebView)findViewById(R.id.webView1);
      browser.getSettings().setJavaScriptEnabled(true);
      browser.setWebViewClient(new MyBrowser());
      browser.loadUrl("file:///android_asset/index.html");
   


   @SuppressLint("JavascriptInterface")
   public void open(View view)
      String url = field.getText().toString();
      browser.getSettings().setLoadsImagesAutomatically(true);
      browser.getSettings().setJavaScriptEnabled(true);
      browser.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
      browser.loadUrl(url);
      browser.addJavascriptInterface(new Object()
      
          @JavascriptInterface
        public void performClick()
        
            Log.d("LOGIN::", "Clicked");
             Toast.makeText(MainActivity.this, "Login clicked", Toast.LENGTH_LONG).show();
        
      , "login");

   
   private class MyBrowser extends WebViewClient 
      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) 
         view.loadUrl(url);
         return true;
      
   

   @Override
   public boolean onCreateOptionsMenu(Menu menu) 
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   

  

但是没有调用 performClick() 方法。 请更正错误。

【问题讨论】:

AndroidManifest 中的代码 参考这个***.com/questions/4065312/… @Hardik 我也给出了上面相同的链接,并引用了相同的链接,但没有工作......请看看我的代码 【参考方案1】:

这就是我的实现方式:

public class FirstActivity extends Activity 

WebView mWebView;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);

    mWebView = (WebView) findViewById(R.id.webView1);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
    mWebView.loadUrl("file:///android_asset/html/File1.html");


public class WebAppInterface 

    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) 
        mContext = c;
    

    /** Show a toast from the web page */
    @JavascriptInterface
    public void nextScreen(String pro_cat_id) 

            startActivity(new Intent(mContext,
         MainActivity.class));
    

并且,在 html 文件中:

javascript:file3.js

function saveId(_id)

    localStorage.setItem("id", _id);
    Android.nextScreen(_id);

HTML:

<html>
    <head>
        <script type="text/javascript" src="arel/js/File3.js"></script>
    </head>
    <body>
        <button onClick="saveId('1');">1</button>
        <button onClick="saveId('2');">2</button>
    </body>
</html>

【讨论】:

【参考方案2】:

尝试替换这个

 browser.addJavascriptInterface(new Object()
      
          @JavascriptInterface
        public void performClick()
        
            Log.d("LOGIN::", "Clicked");
             Toast.makeText(MainActivity.this, "Login clicked", Toast.LENGTH_LONG).show();
        
      , "login");

到这里

Button btnLogin=new Button(ctx);
btnLogin.setOnClickListener(this);

browser.addJavascriptInterface(btnLogin,"login");

@Override
public void onClick(View v) 

        //do Something


在 index.html 中

<html>  <head>  <script language="javascript">  function js1() 
    document.loginform.method="post";  document.loginform.action = "https://example.com/chechlogin.asp";
           
     </script>  </head>  <body>    <form name="loginform">
     <input type="text" name="empcode" value="58686" /><br/>
     <input type="password" name="emppassNTL" />
     <input type="submit" name="submit" id="submit_id" onclick="btnLogin.performClick();" />

更多信息在这里:https://developer.android.com/guide/webapps/webview.html#BindingJavaScript

【讨论】:

html 文件中的 btnLogin 是什么??请解释一下。 @AnujSharma "btnLogin" 是 Button 类变量。当您想通过代码执行点击时,您必须调用“performClick()”方法。看这里developer.android.com/reference/android/view/… 创建按钮时的ctx是什么【参考方案3】:

您需要创建一个 JavaScript 接口并将其从 Android 传递到 JavaScript。然后,您可以将此接口用作传递带参数的函数调用的桥梁。

更多细节和例子在这里:http://developer.android.com/guide/webapps/webview.html#BindingJavaScript

【讨论】:

【参考方案4】:

哎呀!!! performClick() 方法在错误的地方。 MainActivity.java 应该是这样的:

package com.example.webview;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity 

   private WebView browser;

   @Override        
   protected void onCreate(Bundle savedInstanceState) 
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      browser = (WebView)findViewById(R.id.webView1);
      browser.getSettings().setJavaScriptEnabled(true);
      browser.getSettings().setLoadsImagesAutomatically(true);
      browser.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
      browser.setWebViewClient(new MyBrowser());
      browser.loadUrl("file:///android_asset/index.html");
   


   private class MyBrowser extends WebViewClient 
      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) 
          view.loadUrl(url); 
          view.addJavascriptInterface(new Object()
          
              @JavascriptInterface
            public void performClick() throws Exception
            
                Log.d("LOGIN::", "Clicked");
                 Toast.makeText(MainActivity.this, "Login clicked", Toast.LENGTH_LONG).show();
            
          , "login");
         return true;
      
   

   @Override
   public boolean onCreateOptionsMenu(Menu menu) 
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   


【讨论】:

【参考方案5】:

网页代码:

HTML 代码:

 <button class="btn btn-success w-md waves-effect waves-light" id="btnsubmit" type="button" tabindex="3" onclick="getValues();ok.performClick(this.value);"> @Utility.GetDisplayName(Utility.ResourceKey.lblClicktoApp)</button>

jQuery :

var model = 
            "_id": nationalid,//if need to send as argument
            "btnId":"btnsubmit"
        ;
        function getValues() 
            document.getElementById("btnsubmit").value = _id

        
        document.getElementById("btnsubmit").addEventListener("click", function () 
            webkit.messageHandlers.callbackHandler.postMessage(model);
        );

安卓:

 act_webview_WebView.addJavascriptInterface(MyJavaScriptInterface(mContext),"ok")

            act_webview_WebView!!.webViewClient = object : WebViewClient() 


                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean 
                    view?.loadUrl(url)

                    return true
                

                override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) 
                    super.onPageStarted(view, url, favicon)
                    try 
                        webview_progressBar.visibility = View.VISIBLE
                     catch (e: Exception) 
                        e.printStackTrace()
                    
                

                override fun onPageFinished(view: WebView?, url: String?) 
                    super.onPageFinished(view, url)
                    try 
                        webview_progressBar.visibility = View.GONE
                     catch (e: Exception) 
                        e.printStackTrace()
                    

                

                override fun onReceivedError(
                    view: WebView?,
                    request: WebResourceRequest?,
                    error: WebResourceError?
                ) 
                    super.onReceivedError(view, request, error)

                    try 
                        webview_progressBar.visibility = View.GONE
                     catch (e: Exception) 
                        e.printStackTrace()
                    
                
            
            act_webview_WebView!!.loadUrl(URL)

act_webview_WebView.addJavascriptInterface(new Object() @Javascript接口 公共无效执行点击() Log.d("登录::", "点击"); Toast.makeText(MainActivity.this, "点击登录", Toast.LENGTH_LONG).show(); , "登录");

Proguard:

# For webview
#Start
#-keep class * extends android.webkit.WebChromeClient  *; 
#-dontwarn im.delight.android.webview.*
-keep class android.support.v8.renderscript.**  *; 
-keepclassmembers class apppackage.WebviewFragments 
   public *;

-dontwarn
-keepattributes Signature
-keepattributes SetJavaScriptEnabled
-keepattributes JavascriptInterface
-keepattributes InlinedApi
-keepattributes SourceFile,LineNumberTable
-keepattributes *Annotation*

-keepclassmembers class * 
    @android.webkit.JavascriptInterface <methods>;


-keepclassmembers class * 
    @android.webkit.JavascriptInterface <methods>;


-keepclassmembers class **.*$MyJavaScriptInterface 
    *;

-keepclassmembers class **.*$JavaScriptInterface 
    *;


-keep public class **.*$MyJavaScriptInterface
-keep public class **.*$JavaScriptInterface
#END

【讨论】:

以上是关于Activity中Webview的Html按钮点击检测(java代码)的主要内容,如果未能解决你的问题,请参考以下文章

通过Android WebView中的javascript检测点击HTML按钮

通过js调用android原生方法

通过js调用android原生方法

Android Webview Back按钮适用于模拟器,但不适用于设备

如何基于按钮单击在新屏幕上打开webview中的URL

android webView 当用loadDataWithBaseURL加载本地html时如何实现后退到上一页面