javascript - 在 android 中使用 Javascript 桥

标签 javascript android

我只是想将我的 java 应用程序与 webview 上的内容进行通信。

详细来说,可能只是在单击按钮时显示 toast ?

在谷歌上搜索并做了一些研究后,得到以下代码。

P.S:- 我使用的是 Android Studio,是否需要编译任何外部库才能完成任务?还是别的?

以下是我的 WebviewActivity 代码:-

public class WebviewActivity extends AppCompatActivity {

private static final String TAG = "Main";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview);
    //WebView Object
    WebView browser;
    browser=(WebView)findViewById(R.id.webView);
    //Enable Javascript
    browser.getSettings().setJavaScriptEnabled(true);
    //Inject WebAppInterface methods into Web page by having Interface 'Android'
    browser.addJavascriptInterface(new WebAppInterface(this), "Android");
    browser.loadUrl("http://www.somewebsite.com/app/form.html");
}
//Class to be injected in Web page
public class WebAppInterface {
    Context mContext;

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

    /**
     * Show Toast Message
     * @param toast
     */
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }

    /**
     * Show Dialog
     * @param dialogMsg
     */
    public void showDialog(String dialogMsg){
        AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();

        // Setting Dialog Title
        alertDialog.setTitle("JS triggered Dialog");

        // Setting Dialog Message
        alertDialog.setMessage(dialogMsg);

        // Setting alert dialog icon
        //alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(mContext, "Dialog dismissed!", Toast.LENGTH_SHORT).show();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    /**
     * Intent - Move to next screen
     */
    public void moveToNextScreen(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        // Setting Dialog Title
        alertDialog.setTitle("Alert");
        // Setting Dialog Message
        alertDialog.setMessage("Are you sure you want to leave to next screen?");
        // Setting Positive "Yes" Button
        alertDialog.setPositiveButton("YES",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        //Move to Next screen

                    }
                });
        // Setting Negative "NO" Button
        alertDialog.setNegativeButton("NO",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // Cancel Dialog
                        dialog.cancel();
                    }
                });
        // Showing Alert Message
        alertDialog.show();
     }
  }
}

form.html:-

 <html>
 <head>
  <style>
  body{
 background-color: #FA5858;
color:#fff;
  }
input{
background-color: #F7D358;
width: 300px;
padding:10px;
color: #000;
 }
 div#content{
 padding:20px;
 background-color: #F7D358;
  color: #000;
 }
 </style>
 <script type="text/javascript">
  function showAndroidToast(toastmsg) {
    Android.showToast(toastmsg);
   }
 function showAndroidDialog(dialogmsg) {
      Android.showDialog(dialogmsg);
   }
  function moveToScreenTwo() {
    Android.moveToNextScreen();
   }
 </script>
  </head>
  <body>
  <center>
  <h3>Binding JavaScript code to Android code</h3>
      <div id="content">
//some content here
         </div>
     <div>
   Here are few examples:
     </div>
  <div>
       <input type="button" value="Make Toast" onClick="showAndroidToast('Toast made by Javascript')" /><br/>
       <input type="button" value="Trigger Dialog" onClick="showAndroidDialog('This dialog is triggered by Javascript ')" /><br/>
        <input type="button" value="Take me to Next Screen" onClick="moveToScreenTwo()" />
          </div>
      </center>
     </body>
    </html>

我有上面的代码,但它不能在 android-studio 中工作,尝试了所有的可能性,所以最后在这里发布了我的问题。

我对此的研究:-

https://developer.android.com/guide/webapps/webview.html
https://developer.android.com/reference/android/webkit/WebView.html
http://stackoverflow.com/questions/4325639/android-calling-javascript-functions-in-webview

最佳答案

WebAppInterface 类中的方法缺少 @JavascriptInterface 注释。

你的 WebAppInterface 类应该是这样的,

public class WebAppInterface {
    Context mContext;

    WebAppInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public void showToast(String toast) {
    }

    @JavascriptInterface
    public void showDialog(String dialogMsg){
    }

    @JavascriptInterface
    public void moveToNextScreen(){
    }

}

编辑

在将网页内容加载到 WebView 时,请不要忘记将您的应用限制为 API17+,否则您的应用将容易受到攻击。阅读下面@Robert 的评论。

关于javascript - 在 android 中使用 Javascript 桥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39657311/

相关文章:

asp.net - “AjaxControlToolkit”是未定义的错误

java - 如何为 Retrofit 中的挂起功能创建调用适配器?

java - API key 配置android

java - 如何将 setContentView(View view) 方法移动到 fragment

android - android中的xml解析

android - 如何设置android接近警报的准确性

javascript - javascript 对象中的依赖项

javascript - 如何验证 html 页面并使用 javascript 修复它

javascript - 如果可以评估它并防止异常,如何安全地使用 eval() javascript 来获得指示?

javascript - 使用express和bodyparser渲染为html文件