在Android WebView中运行Javascript-onPageFinished循环

Running Javascript in Android WebView - onPageFinished Loop

本文关键字:Javascript-onPageFinished 循环 运行 Android WebView      更新时间:2023-09-26

我在使用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");

    }

我现在想做的就是测试JS是否能够在页面加载"test"值后正确填充文本框;尝试运行时刷新(看到"页面已完成加载"的重复logcat打印):

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

这是在Android中尝试将一些JS注入WebView的正确方法吗?抱歉,如果有明显的遗漏,我的大部分经验都在斯威夫特身上。

如有任何帮助,我们将不胜感激。

感谢

在编写代码之前尝试"javascript:"。我用这个,效果很好:

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