【发布时间】:2014-07-08 09:10:13
【问题描述】:
我目前正在创建一个安卓应用程序。
该应用程序的目的是将一些注入的 JavaScript 代码触发到我在我的 android 应用程序中创建的 WebView 中。我遇到的问题是已注入的操作不起作用。
您还应该知道,我正在加载的 html 页面是在本地创建的。该应用程序的目的是显示吐司消息。代码清单如下:
//uses javascript that is in the local HTML file
public class MainActivity extends Activity {
final String URL = "file:///android_asset/index.html";
private WebView myWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
String test= "test";
String javascript ="javascript:document.addEventListener('click', function(){Android.showToast(toast)})";
myWebView.loadUrl(javascript);
myWebView.loadUrl(URL);
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
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 showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
}
【问题讨论】:
-
在
showToast方法中注入的toast变量在哪里定义?您的问题可能是在您的 javascript 回调范围内无法访问此变量。 -
show toast 的声明在底部。我知道代码有效,因为它在我从 HTML 中启动时有效。但是,我想做的是让它通过java注入并以这种方式运行。
-
我没有要求声明
showToast方法,而是要求你传递给showToast的toast变量的定义。我想这个变量是在你的 javascript 代码中声明和定义的,但想知道在哪里(即你可以发布你的 javascript 代码的相关部分吗?)。 -
对不起我的错误。 toast 变量没有正确的定义。 public void showToast(String toast) 没有定义它。我知道吐司位有效,所以我认为它与实际的javascript有关。具体行是:"javascript:document.addEventListener('click', Android.showToast)";
-
@Sztucki 可以提供一个带有最终 html 输出的 jsfiddle 示例。
标签: java javascript android webview code-injection