问题描述
我尝试在 android 客户端应用程序的 webview 中填写表单.我知道它应该如何工作,但 getElementById 总是为我返回 null.我在不同的网站上尝试过.
I try to fill out a form inside a webview from the android client app. I know how it should work, but the getElementById always returns null for me. I tried it on different websites.
这是我的 www.google.com 示例.
Here is my example for www.google.com.
MyWebView view = new MyWebView(this);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl("http://www.google.com");
view.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView v, String url) {
v.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView v, String url) {
v.loadUrl("javascript:document.getElementById('mib').value = 'aaa';");
}
});
setContentView(view);
还有 MyWebView 类(仅供参考).
And the MyWebView class (only for information).
class MyWebView extends WebView {
Context context;
public MyWebView(Context context) {
super(context);
this.context = context;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// do some multi touch stuff
return true;
}
}
我总是收到错误:
09-01 04:35:26.453: I/chromium(2962): [INFO:CONSOLE(1)] "Uncaught TypeError: Cannot set property 'value' of null", source: https://www.google.de/?gws_rd=ssl (1)
但是元素mib"应该在网站上.使用桌面浏览器(带有移动模拟的 chrome)一切正常.我不知道,这里出了什么问题.
But the element "mib" should be on the site. Using a desktop browser (chrome with mobile simulation) everything is working fine. I have no idea, whats going wrong here.
感谢提示!
我取得了一些进展.关于 this 站点,我还需要 setDomStorageEnabled(true).不,我可以找到 DOM 对象并设置值,但是我没有显示修改后的站点,而是得到一个只有我设置的值的新空白站点.例如.带有文本aaa"的白色空白站点.
I got some progress. Regarding this site, I also need setDomStorageEnabled(true).No I can find the DOM object and set the value, but instead of showing the modified site I get a new blank one with only the value I set. E.g. a white blank site with the text "aaa".
推荐答案
我终于找到了解决方案!这是一种非常奇怪的行为.
Finally I found a solution! And it is a really strange behaviour.
首先你需要在你的 webview 上指定 setDomStorageEnabled(true).否则 DOM 不起作用.我想知道为什么没有教程给出提示.不过还好.
First of all you need to specify setDomStorageEnabled(true) on your webview. Otherwise the DOM doesn't work. I wonder why no tutorial gave a hint about. But ok.
myview.getSettings().setDomStorageEnabled(true);
在此之后,我最终在一个白色的空白页中,只有我设置的值.奇怪的是, javascript:document.getElementById('myfield').value = 'aaa';
返回一个值.即我设置的那个.因此创建了一个仅包含字符串aaa"的新空白页面.
After this I ended up in a white blank page with only the value I set. The strange thing is, that javascript:document.getElementById('myfield').value = 'aaa';
returns a value. Namely the one I set. So a new blank page was created that only contains the string "aaa".
我通过修改javascript扔掉返回结果解决了:
I solved it by modifying the javascript to throw away the return result:
javascript:var x = document.getElementById('myfield').value = 'aaa';
瞧.它正在工作.
这篇关于Android WebView 总是在 loadUrl 上为 javascript getElementById 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!