android: webview not loading javascript with custo

2019-05-22 08:14发布

I've got a very basic WebView which works until I try to add a custom webViewClient where it stops processing JavaScript. Am I doing something wrong? Is there another way to get rid of the address bar and menu options in the WebView?

    browser = (WebView) findViewById(R.id.webkit);

    WebSettings webSettings = browser.getSettings();
    webSettings.setJavaScriptEnabled(true);

    // uncommenting this line will remove address bar, but also stop JavaScript from loading
    //browser.setWebViewClient(new InternalWebViewClient());

    // even uncommenting this line will stop JavaScript from loading
    //browser.setWebViewClient(new WebViewClient());

    browser.setWebChromeClient(new InternalWebChromeClient());
    if (savedInstanceState != null) {
        browser.restoreState(savedInstanceState);
    } else {
        browser.loadUrl("http://site.with.javascript");
    }

3条回答
闹够了就滚
2楼-- · 2019-05-22 08:56

In my app I use the following and there is no address bar, and JavaScript works (modified to match your naming):

browser = (WebView) findViewById(R.id.webkit);
browser.getSettings().setJavaScriptEnabled(true);

browser.loadUrl("http://site.with.javascript");

I don't do anything with setWebViewClient or setWebChromeClient and it works as described.

I think the problem with your code is that you enable JavaScript on the default (Internal)WebViewClient and/or WebChromeClient then you replace those with new ones that now have new properties.

If you move the setJavaScriptEnabled(true) call to come after those new assignments (and before the loadUrl I think your code would work.

查看更多
Fickle 薄情
3楼-- · 2019-05-22 08:59

For some reason the webkit runs JS differently than the browser - I ended up getting around the issue by forcing some JS to run with the following line after the page had loaded:

browser.loadUrl("javascript:document.getElementById('something').do.something()");
查看更多
做个烂人
4楼-- · 2019-05-22 09:05

I was helped by such a decision. Wrap computing in an anonymous function.

"javascript:" + "(function(){ <YOUR CODE> })();"
查看更多
登录 后发表回答