2012-01-21 45 views
4

所以,在阅读围绕我读,我可以“注入”的JavaScript到加载的网页以编程方式填充网站的形式,所以我尝试以下操作:在WebView中使用JavaScript

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    WebView WebView; 
    WebView = (WebView) findViewById(R.id.webview); 
    WebView.setWebViewClient(new HelloWebViewClient()); 
    WebView.getSettings().setJavaScriptEnabled(true); 
    WebView.getSettings().setBlockNetworkImage(false); 
    WebView.loadUrl("http://www.kingsage.es"); 
    String username = "XXX"; 
    String Password = "YYY"; 
    WebView.loadUrl("javascript:document.getElementById('login_player').value='"+username+"';javascript:document.getElementById('login_passwd').value = '"+Password+"';"); 
} 

然而,当我运行这个在模拟器上,我收到一个错误,好像无法找到网站。如果我关闭第二个loadUrl方法我加载网站,但我需要以编程方式填写登录表格!,我想我做错了什么,但我没有找到并回答周围的阅读。任何帮助,将不胜感激!!

+0

它甚至显示网站开始? www.google.com试试看看它是否显示出来。 – JoxTraex

+0

对我的解决方案有帮助吗? – JeanLuc

回答

6

则需要等到网页加载(使用WebViewClient),然后执行你的JavaScript

webView.setWebViewClient(new WebViewClient(){ 
    @Override 
    public void onPageFinished (WebView webView, String url) 
    { 
     webView.loadUrl("javascript:document.getElementById('login_player').value='"+username+"';javascript:document.getElementById('login_passwd').value = '"+Password+"';"); 
    } 
}); 

同时也要确保你只执行一次,而不是在每一个onPageFinished事件

+0

需要帮助! http://stackoverflow.com/questions/33249207/android-webview-auto-sign-in – Juni

1

我喜欢JeanLuc的建议它对我来说98%的工作。我仍然需要自动登录用户进入网页,一旦他们的用户名和密码已经输入,所以我做了以下工作,并且运行良好,除了试图删除“您是否想记住密码”消息。

@Override 
      public void onPageFinished (WebView webView, String url) 
      { 
        webView.loadUrl("javascript:document.getElementById('Login1_UserName').value='"+userName+"';javascript:document.getElementById('Login1_Password').value = '"+password+"';"); 
        webView.loadUrl("javascript:document.getElementById('Login1_LoginButton').click();"); 
      } 

的第二行的“登录”按钮,并在自动登录他们。希望它可以帮助别人。

+0

我可以在一个网站上应用相同的代码,我不拥有?需要紧急回复...因为我有问题 – Juni

+0

这段代码是针对一个网站的,我没有任何控制权。所以如果我理解了你的问题,那么答案是肯定的。 – timv

+0

我刚刚取代了一些值,并在我的页面上实现完成,但没有做我想要的东西...我想我不喜欢发帖子的另一个问题 – Juni

0

这是我如何来达到的它在我的情况,我必须浏览一个页面,填写文本框和提交

WebView webView = FindViewById<WebView>(Resource.Id.webEspView); 
webView.SetWebViewClient(new Client()); 
webView.Settings.JavaScriptEnabled = true; 
webView.LoadUrl("http://192.168.4.1") 

然后添加客户端类并重载onPageFinished()方法。

public class Client : WebViewClient 
{ 
    public override void OnPageFinished(WebView view, string url) 
    { 
     base.OnPageFinished(view, url); 
     string ssid = Variables.GetInitialUsername();   
     ssid = ssid.Trim(new char[] {'\"'}); 
     string pass = Variables.GetInitialPassword(); 

     var script = $"document.getElementById(\"clientId\").value = \"{ssid}\";" + 
        $"document.getElementById(\"branchId\").value = \"{pass}\";" +       
        "document.querySelector('button[type=\"submit\"]').click()";   
     view.LoadUrl($"javascript: {script}"); 


    } 
} 

希望它有帮助。

相关问题