這篇文章帶給大家的內容是關於JavaScript互動的程式碼範例,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Carson</title> <script> function callAndroid(){ test.hello("js调用了android中的hello方法"); } function returnResult(){ alert("result is"); } </script> </head> <body> <button type="button" id="button1" onclick="callAndroid()"> 调用安卓代码 </button> </body> </html>
package com.example.webjs; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button tojs; WebView webView; @SuppressLint("JavascriptInterface") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = findViewById(R.id.web_id); tojs = findViewById(R.id.calljs_but_id); WebSettings webSettings = webView.getSettings(); // 设置与Js交互的权限 webSettings.setJavaScriptEnabled(true); // 设置允许JS弹窗 webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //设置对象映射 webView.addJavascriptInterface(new JsToAndroid() , "test"); // 先载入JS代码 // 格式规定为:file:///android_asset/文件名.html webView.loadUrl("file:///android_asset/text.html"); alteView(webView); tojs.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String result = "你好"; // webView.loadUrl("javascript:returnResult(" + result + ")"); webView.loadUrl("javascript:returnResult()"); } }); } public class JsToAndroid{ @JavascriptInterface public void hello(final String str ){ runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this , str , Toast.LENGTH_LONG).show(); } }); } } public void alteView(WebView webView){ // webView.setWebChromeClient(new WebChromeClient()); webView.setWebChromeClient(new WebChromeClient(){ @Override public boolean onJsAlert(WebView view, String url, String message, final JsResult result) { Log.e("tag" ,"执行次数"); AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this); b.setTitle("Alert"); b.setMessage(message); b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); b.setCancelable(false); // b.create().show(); return super.onJsAlert(view, url, message, result); } }); } }
以上是JavaScript互動的程式碼範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!