android: webview not loading javascript with custom WebViewClient

柔情痞子 提交于 2020-01-14 02:47:26

问题


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");
    }

回答1:


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.




回答2:


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()");



回答3:


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

"javascript:" + "(function(){ <YOUR CODE> })();"


来源:https://stackoverflow.com/questions/3423579/android-webview-not-loading-javascript-with-custom-webviewclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!