无法从Android活动中调用javascript
我试图在一个xhtml页面中调用一个简单的高亮显示此文本javascript函数,该页面加载在assets文件夹中,并显示在Android活动的WebView中。使用以下功能:无法从Android活动中调用javascript,javascript,android,android-webview,Javascript,Android,Android Webview,我试图在一个xhtml页面中调用一个简单的高亮显示此文本javascript函数,该页面加载在assets文件夹中,并显示在Android活动的WebView中。使用以下功能: 1. 加载URL(“javascript:myFunc(param)”)不起作用。 2.在loadUrl中内联整个函数也不起作用。 3.我还尝试在单独的文件(highlighter.js)和xhtml正文部分(使用CDATA标记)中使用突出显示功能 上述方法都不起作用。我需要帮助找出我做错了什么 The code:
1. <代码>加载URL(“javascript:myFunc(param)”)代码>不起作用。
2.在
loadUrl
中内联整个函数也不起作用。3.我还尝试在单独的文件(highlighter.js)和xhtml正文部分(使用CDATA标记)中使用突出显示功能 上述方法都不起作用。我需要帮助找出我做错了什么
The code:
/* JSWebview:
* 1. Loads a webpage in the external sdcard.
* 2. enables javascript and runs a small script.
*/
package com.sriram.jswebview;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private WebView wv = null;
private String url = null;
private JSInterface myJSI;
private Button fromMain;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadPage();
//wv.loadUrl("javascript:doecho(\"Hello World!\");");
//wv.loadUrl("javascript:tostring());");
String toFind = "Hello";
Log.v(this.toString(), "Finding string = " + toFind);
//find string and highlight.
if(android.os.Build.VERSION.SDK_INT < 16) {
Log.v(this.toString(), "Launching findAll.");
int num = wv.findAll(toFind);
Log.v(this.toString(), num + " instances found.");
} else {
Log.v(this.toString(), "Searching with findAllAsync.");
wv.findAllAsync(toFind);
}
fromMain = (Button) findViewById(R.id.fromMain);
fromMain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String message = "This is a test.";
wv.loadUrl("javascript:callFromActivity(\""+message+"\")");
//wv.loadUrl("javascript:function (msg) { var oldHTML = document.getElementById(\"highlightbegin\"); var newHTML = \"<span style=\'color:#ffa000\'>\" + msg + \"</span>\"; document.getElementById(\"highlightbegin\").innerHTML = newHTML;}");
}
});
}
@SuppressLint("SetJavaScriptEnabled")
@SuppressWarnings("deprecation")
public void loadPage() {
//loads the index.xhtml page from /mnt/sdcard.
Log.v(this.toString(), "Inside loadPage().");
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//external media is mounted.
url = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "index.xhtml";
Log.v(this.toString(), "URL = " + url);
}
wv = (WebView) findViewById(R.id.wv);
wv.getSettings().setJavaScriptEnabled(true); //enable javascript.
myJSI = new JSInterface(this.getApplicationContext(), wv);
wv.addJavascriptInterface(myJSI, "JSInterface");
if((wv != null) && (url != null)) {
Log.v(this.toString(), "Inside loadurl.");
//wv.loadUrl(url);
wv.loadUrl("file:///android_asset/mypage.xhtml");
}
}
@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;
}
}
//this class is used to call Javascript functions that act on the html page.
class JSInterface {
private WebView wv = null;
private Context c;
public JSInterface(Context context, WebView w) {
Log.v(this.toString(), "Inside JSInterface constructor.");
c = context;
wv = w;
}
public String tostring() {
//Log.v(this.toString(), "Inside toString()");
String result = "injected Object";
return result;
}
public void doecho(String x) {
Log.v(this.toString(), "Inside doEcho of JSInterface.");
Toast.makeText(wv.getContext(), x, Toast.LENGTH_SHORT).show();
}
public void showToast(String message) {
Toast.makeText(c, message, Toast.LENGTH_LONG).show();
}
public void openAndroidDialog() {
AlertDialog.Builder myDialog = new AlertDialog.Builder(c);
myDialog.setTitle("DANGER!");
myDialog.setMessage("You can do what you want!");
myDialog.setPositiveButton("ON", null);
myDialog.show();
}
}
代码:
/*JSWebview:
* 1. 在外部SD卡中加载网页。
* 2. 启用javascript并运行一个小脚本。
*/
包com.sriram.jswebview;
导入android.annotation.SuppressLint;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.content.Context;
导入android.os.Bundle;
导入android.os.Environment;
导入android.util.Log;
导入android.view.Menu;
导入android.view.view;
导入android.webkit.WebView;
导入android.widget.Button;
导入android.widget.Toast;
公共类MainActivity扩展了活动{
私有网络视图wv=null;
私有字符串url=null;
私有JSI接口myJSI;
主菜单的私有按钮;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadPage();
//loadUrl(“javascript:doecho(\“Hello World!\”);”;
//loadUrl(“javascript:tostring());”;
String toFind=“Hello”;
Log.v(this.toString(),“Finding string=“+toFind”);
//查找字符串并突出显示。
if(android.os.Build.VERSION.SDK_INT<16){
Log.v(this.toString(),“启动findAll”);
int num=wv.findAll(toFind);
Log.v(this.toString(),num+“找到实例”);
}否则{
Log.v(this.toString(),“使用findAllAsync进行搜索”);
wv.findAllAsync(toFind);
}
fromMain=(按钮)findViewById(R.id.fromMain);
fromMain.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
String message=“这是一个测试。”;
loadUrl(“javascript:callFromActivity(\“”+message+“\”));
//wv.loadUrl(“javascript:function(msg){var oldHTML=document.getElementById(\“highlightbegin\”);var newHTML=\“\”+msg+\”;document.getElementById(\“highlightbegin\”)。innerHTML=newHTML;}”);
}
});
}
@SuppressLint(“SetJavaScriptEnabled”)
@抑制警告(“弃用”)
公共void加载页(){
//从/mnt/sdcard加载index.xhtml页面。
Log.v(this.toString(),“Inside loadPage()”;
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
//外部介质已装入。
url=Environment.getExternalStorageDirectory().getAbsolutePath()+“/”+“index.xhtml”;
Log.v(this.toString(),“URL=“+URL”);
}
wv=(WebView)findviewbyd(R.id.wv);
wv.getSettings().setJavaScriptEnabled(true);//启用javascript。
myJSI=新的JSInterface(this.getApplicationContext(),wv);
addJavascriptInterface(myJSI,“JSInterface”);
如果((wv!=null)&&(url!=null)){
Log.v(this.toString(),“Inside loadurl”);
//wv.loadUrl(url);
wv.loadUrl(“file:///android_asset/mypage.xhtml");
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.main,menu);
返回true;
}
}
//此类用于调用作用于html页面的Javascript函数。
类JSF接口{
私有网络视图wv=null;
私有上下文c;
公共JS接口(上下文,WebView w){
Log.v(this.toString(),“内部JSInterface构造函数”);
c=上下文;
wv=w;
}
公共字符串tostring(){
//Log.v(this.toString(),“Inside-toString()”;
String result=“注入对象”;
返回结果;
}
公共void doecho(字符串x){
Log.v(this.toString(),“JSInterface的doEcho内部”);
Toast.makeText(wv.getContext(),x,Toast.LENGTH_SHORT.show();
}
公共void showtoos(字符串消息){
Toast.makeText(c,message,Toast.LENGTH_LONG).show();
}
public void openAndroidDialog(){
AlertDialog.Builder myDialog=新建AlertDialog.Builder(c);
myDialog.setTitle(“危险!”);
setMessage(“你可以做你想做的事!”);
myDialog.setPositiveButton(“开”,空);
myDialog.show();
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/fromMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="fromMain" />
<WebView
android:id="@+id/wv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_world"
android:layout_above="@id/fromMain" />
</RelativeLayout>
mypage.xhtml(存在于资产文件夹中:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="application/xhtml+xml;charset=UTF-8" />
<title>My HTML</title>
</head>
<body>
<h1>MyHTML</h1>
<p id="highlightbegin">Hello World! This is a test.</p>
<div> <input type="button" value="Alert" onclick="displayAlert()" /> </div>
<div> <input type="button" value="Say hello" onclick="showAndroidToast('Hello Android!')" /> </div>
<div> <input type="button" value="Open Dialog" onclick="openAndroidDialog()" /> </div>
<div> <input type="button" value="Add highlight" onclick="changeColor()" /> </div>
<script type="text/javascript">
//<![CDATA[
function showAndroidToast(toast) {
JSInterface.showToast(toast);
}
function openAndroidDialog() {
JSInterface.openAndroidDialog();
}
function displayAlert() {
window.alert("I am here!");
}
//]]>
</script>
<script src="doecho.js" type="text/javascript"> </script>
<script src="tostring.js" type="text/javascript"> </script>
<script src="highlighter.js" type="text/javascript"> </script>
</body>
</html>
我的HTML
MyHTML
你好,世界!这是一个测试
//
highlighter.js(包含javascript函数):
函数callFromActivity(msg){
警报(msg);
var oldHTML=document.getElementById(“highlightbegin”);
警报(oldHTML);
var newHTML=“+msg+”;
警报(newHTML);
document.getElementById(“mytext”).innerHTML=newHTML;
}
您针对的是哪个API版本?此外,您可能需要在每个JSInterface
方法之前添加@JavascriptInterface
。此外,您在哪里调用highlighter函数?MinSDK=8和target=17。highlighter.js是一个包含javascript函数callFromActivity
的文件。此函数为call单击Main中的按钮时,此按钮将被禁用。
function callFromActivity(msg) {
alert(msg);
var oldHTML = document.getElementById("highlightbegin");
alert(oldHTML);
var newHTML = "<span style='color:#ffa000'>" + msg + "</span>";
alert(newHTML);
document.getElementById("mytext").innerHTML = newHTML;
}