问题描述
我想知道为什么我的JavaScript不会在我的WebView中执行。
I would like to know why my JavaScript won't execute in the my WebView.
在我的应用程序中,我显示一个自定义webview通过覆盖 MainActivity
的 onCreate
来查看应用程序。
In my app, I am displaying a custom webview on top of the main view on app start by overriding MainActivity
's onCreate
. The webview is filled with HTML and Javascript from a file.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Display display = getWindowManager().getDefaultDisplay();
// The next line creates webview with the content from my html file that contains javascript.
WebView loadingScreen = Loading.createLoadingScreen(this, getLoadingHTMLPath(), appView);
LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
loadingScreen.setLayoutParams(layoutParams);
loadingScreen.setMinimumHeight(display.getHeight());
loadingScreen.setMinimumWidth(display.getWidth());
Dialog loadingDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
loadingDialog.setContentView(loadingScreen);
loadingDialog.setCancelable(false);
loadingDialog.show();
这会成功显示我的WebView,但是没有执行JavaScript。 (HTML文件在< body>
后包含< script>
标记)我很困惑,方法在iOS和它的工作。
This successfully displays my WebView, but no JavaScript in it is executed. (The HTML file contains <script>
tag after <body>
) I am confused because I have taken similar approach in iOS and it worked.
我的着墨是我不能在 onCreate
,但我不知道。
My inkling is that I am not able to execute JavaScript in the onCreate
stage, but I am not sure. Any suggestions as to why this happens and possible solutions?
推荐答案
问题是我不得不使用 WebSettings#setJavaScriptEnabled
以启用JavaScript执行。
The problem was that I had to use WebSettings#setJavaScriptEnabled
to enable JavaScript execution.
默认情况下,设置 setJavaScriptEnabled
到 false
。这是为什么我的JavaScript没有运行。
By default, the setJavaScriptEnabled
is set to false
. That was why my JavaScript was not running.
在我的例子中,我不得不添加:
In my case, I had to add:
loadingScreen.getSettings().setJavaScriptEnabled(true);
这篇关于Cordova Android:没有js当在应用程序启动时显示自定义webview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!