控制WebView元素不起作用

时间:2018-02-02 14:21:11

标签: javascript java android android-webview

我已经看了几个关于这个问题的SO帖子,下面是我提出的:

public class MainActivity extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        webView = (WebView) findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setDomStorageEnabled(true);
        webView.loadUrl("http://google.com");

        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String password = "a123345";
        //webView.loadUrl("javascript:document.getElementById('lst-ib').value = '" + "hi" + "';");
        webView.loadUrl("javascript:var uselessvar  = document.getElementByName('q').value='" + password + "';");
        Log.d("d","Done");

    }
}

但我尝试过的一切都没有效果。知道我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

关于此事的几点

  • 尽量避免在主线程中使用Thread.sleep
  • 不要用恒定时间加载脚本
  • 您可以使用类似WebViewClient回调的回调,这些回调至少有onPageFinished方法可用于加载JS
  • 添加setJavaScriptEnabled以运行JS

示例:

WebView webView = (WebView) findViewById(R.id.webView);

webView.setWebViewClient(new WebViewClient() {
    public void onReceivedError(WebView view, int errorCode, String description,
                                String failingUrl) {
    }

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

    @Override
    public void onPageFinished(WebView view, String url) {
        String password = "a123345";
       view.loadUrl("javascript:(function() { " +
               "document.getElementsByName('q')[0].value = '" + password + "'; " +
               "})()");
    }
});
webView.getSettings().setJavaScriptEnabled(true);

webView.loadUrl("https://google.com");