Javascript 在 WebView Activity 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8711225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:18:36  来源:igfitidea点击:

Javascript not working in a WebView Activity

javascriptandroidwebview

提问by 10ff

I have an Activity that has just a WebView, which contains HTML, CSS and Javascript Code.

我有一个 Activity ,它只有一个WebView,其中包含 HTML、CSS 和 Javascript 代码。

It seems that there's a problem with the accessof Javascriptto the screen sizeof the view. LogCat says:

似乎有与问题访问Java脚本屏幕尺寸的看法。LogCat 说:

(Tag: Web Console): Uncaught TypeError: Cannot call method 'getWidth' of undefined 
at file:///android_asset/Prospekte/grund/html5-player/js/epaper-mobile.js:20

When I look into the js-file, there is: var f=this.body.getWidth();

当我查看 js 文件时,有: var f=this.body.getWidth();

There curious thing is that sometimes the code works. The epaper is shown well. But most time there's this error.

奇怪的是,有时代码会起作用。电子纸显示良好。但大多数时候都会出现这个错误。

    setContentView(R.layout.prospekt_layout);
    final Activity activity = this;

    mWebView = (WebView) findViewById(R.id.prospekt_webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.setWebChromeClient(new WebChromeClient() {
    public void onProgressChanged(WebView view, int progress) {
        activity.setProgress(progress * 1000);
      }
    });

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
        {
            // Handle the error
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            view.loadUrl(url);
            return true;
        }
    });   

    mWebView.loadUrl("file:///android_asset/Prospekte/modKachel/mobile.html");    

The layout is:

布局是:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    >
<WebView
    android:id="@+id/prospekt_webview"
    android:layout_width="900px"
    android:layout_height="900px"
/>
</LinearLayout>

I changed the size of the webView cause I thought that this could be the solution..but it's no working with dp either.

我改变了 webView 的大小,因为我认为这可能是解决方案......但它也不适用于 dp。

Someone has in idea?

有人有想法吗?

回答by Usama Sarwar

Set this setting as well for your webView:

也为您的 webView 设置此设置:

WebSettings settings = webView.getSettings();
settings.setDomStorageEnabled(true);

For Detail refer to answer in the following link: ERROR/Web Console: Uncaught TypeError: Cannot call method 'getItem' of null at http://m.youtube.com/:844

有关详细信息,请参阅以下链接中的答案: 错误/Web 控制台:未捕获的类型错误:无法在 http://m.youtube.com/:844 上调用 null 的方法“getItem”

Update:or adding this might help:

更新:或添加这可能会有所帮助:

webView.loadDataWithBaseURL("fake://fake.com", myString, "text/html", "UTF-8", null);

回答by profuel

You should implicitly enable Javascript execution in your WebView, since this could cause XSS and other vulnerabilities.

您应该在 WebView 中隐式启用 Javascript 执行,因为这可能会导致 XSS 和其他漏洞。

web = new WebView(this);
web.getSettings().setJavaScriptEnabled(true);

Also, I prefer to set my WebViewClient via

另外,我更喜欢通过设置我的 WebViewClient

WebViewClient webViewMainWebClient = new WebViewClient()
{
   // Override page so it's load on my view only
   @Override
   public boolean shouldOverrideUrlLoading(WebView  view, String  url)
   {
       // Return true to override url loading (In this case do nothing).
       return false;
   }
}
web.setWebViewClient(this.webViewMainWebClient);

to let me restrict usage of only my sites.

让我限制只使用我的网站。

回答by Bastien

Got the same problem on android 3.2. A solution that works for me (pretty ugly) is to put a sleep and call another loadUrl, try with more time if 300ms is not sufficient:

在 android 3.2 上遇到了同样的问题。对我有用的解决方案(非常丑陋)是休眠并调用另一个 loadUrl,如果 300 毫秒不够,请尝试更多时间:

myWebView.loadUrl("file:///android_asset/gabarit.html");
try {
    Thread.sleep(300);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
myWebView.loadUrl("file:///android_asset/gabarit.html");

回答by R Earle Harris

I had the same problem with my Mo Da Browser project. I added these two lines:

我的 Mo Da Browser 项目也遇到了同样的问题。我添加了这两行:

    wvOptions.setBuiltInZoomControls(true);
    wvOptions.setUseWideViewPort(true);

wvOptions is just webview.getSettings() stored in a var. The second line seems to have solved the problem. The first line gives users control over the resulting web page's size. You could add the "open in overview" option if you liked the result. That didn't help me so I used the zoom option.

wvOptions 只是存储在 var 中的 webview.getSettings()。第二行似乎解决了问题。第一行让用户控制生成的网页的大小。如果您喜欢结果,可以添加“在概览中打开”选项。这对我没有帮助,所以我使用了缩放选项。