本篇文章给大家带来的内容是关于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交互的代码示例的详细内容。