【问题标题】:Running Javascript in Android WebView - onPageFinished Loop在 Android WebView 中运行 Javascript - onPageFinished 循环
【发布时间】:2015-04-01 15:32:59
【问题描述】:

我在让我的应用程序使用 onPageFinished 方法在页面上正确运行一些 JS 时遇到了一些麻烦。

下面的代码包含在我创建的一个类中,该类扩展了 AsyncTask 以获取和解析保存在其他地方的 JSON 文件。

我能够正确获取 JSON 文件,解析数据并获取并设置 WebView 的 url。一切正常加载,直到我尝试使用 onPageFinished 方法运行一些 JS。

        //onPostExecute method runs when the doInBackground method is completed
    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);

        //Casting as WebView as findViewById doesnt explicity return a value type.
        webView = (WebView) findViewById(R.id.webView);

        //Obtaining the websettings of the webView
        WebSettings webViewSettings = webView.getSettings();

        //Setting Javascript enabled
        webViewSettings.setJavaScriptEnabled(true);

        webView.setWebViewClient(new webViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);


                webView.loadUrl("document.getElementById('field_133').value = 'Test';");
                Log.d("onPageFinished", "The Page has finished loading");

            }
        });

        //Obtaining the first item in the cellRef List Array - From here we will access the Url data for the train operator.
        parsedUrl = cellRef.get(0).getUrl();

        //load the page we parsed from online file
        webView.loadUrl(parsedUrl);
        Log.d("loadUrl", "Now load the parsed Url");



    }

我现在要做的就是测试一旦页面加载了“Test”的值,JS 是否可以正确填充文本框 - 但是,WebView 似乎卡在加载和刷新循环中(在尝试运行时看到“页面已完成加载”的重复 logcat 打印):

webView.loadUrl("document.getElementById('field_133').value = 'Test';");

这是尝试将一些 JS 注入 Android 中的 WebView 的正确方法吗?如果有明显的缺失,我深表歉意,我的大部分经验都在 Swift 中。

任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: javascript android json webview


    【解决方案1】:

    在代码前尝试“javascript:”。 我用这个,效果很好:

    loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()");
    

    【讨论】:

    • 这看起来已经停止了“循环”,但现在我在正确的 URL 处短暂显示了页面(大约 0.5 秒),然后它在左上角显示了一个带有“测试”的白屏Web 视图的。是否需要像从 Switch 中跳出一样包含一种 break 子句?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多