我是一个编程新手,我正在从跟踪网站制作 WebView。问题是,当我在 WebView 中输入跟踪代码时,该网站没有显示任何内容,我将在下一张图片中向您显示:
这是我的代码:
public class MainActivity extends AppCompatActivity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.webview = (WebView)findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.addJavascriptInterface(new WebAppInterface(this), "android");
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(MainActivity.this, "WebView Example", "Loading...");
webview.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url){
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url){
Log.i(TAG, "Finished loading url: " +url);
if (progressBar.isShowing()){
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
Log.e(TAG, "Error: " + description);
Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.show();
}
});
webview.loadUrl("https://geartrack.hdn.pt");
}
public class WebAppInterface{
Context mContext;
WebAppInterface(Context c){
mContext = c;
}
@JavascriptInterface
public void showToast(String toast){
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.action_refresh:
webview.loadUrl("https://geartrack.hdn.pt");
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()){
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
请帮助我。
最佳答案
问题是您尚未启用 LocalStorage为您的 WebView。如果您使用 Chrome inspect通过开发人员工具创建 WebView,您会发现出现错误。具体来说 main.js?v=1:373 Uncaught TypeError: Cannot read property 'length' of null
这是为什么?如果您查看 main.js
中的该行代码,您会发现该脚本正在访问 localStorage
的长度>。它会使脚本崩溃,因为您无法访问 undefined variable 的属性。默认情况下,localStorage
在 WebView 中未定义,因为 DomStorage
未启用。
要解决这个问题。为您的 WebView 启用 LocalStorage 添加行:
settings.setDomStorageEnabled(true);
其中 settings
是 WebView
的 WebSettings
对象。
完成此操作后,一切都会按您的预期进行!
关于javascript - Android WebView不显示网站内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42980464/