I am trying to get the src of a captcha image found in a webview but when i type the below code the output says:
Uncaught TypeError: Cannot read property 'src' of null
and another question if i get the image src how can i put the image in an image view?
any help will be really appreciated
here is my code so far:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView) findViewById(R.id.wv) ;
mImgCaptcha = (ImageView) findViewById(R.id.imgCaptcha);
done = (Button) findViewById(R.id.done);
contentView = (TextView) findViewById(R.id.textView);
username = (EditText) findViewById(R.id.editText);
password = (EditText) findViewById(R.id.password);
code = (EditText) findViewById(R.id.code);
WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
wv.getSettings().setDomStorageEnabled(true);
wv.loadUrl("https://noor.moe.gov.sa/NOOR/Login.aspx");
wv.loadUrl("javascript:var a = document.getElementById('imgCaptcha').src;");
System.out.println(wv.getUrl());
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
wv.loadUrl("javascript:var x = document.getElementById('tbPublic').value = '" + username.getText().toString() + "';");
wv.loadUrl("javascript:var x = document.getElementById('tbPrivate').value = '" + password.getText().toString() + "';");
wv.loadUrl("javascript:var x = document.getElementById('tbCaptcha').value = '" + code.getText().toString() + "';");
try {
Thread.sleep(2000);
wv.loadUrl("javascript:(function(){" +
"l=document.getElementById('btnLogin');" +
"e=document.createEvent('HTMLEvents');" +
"e.initEvent('click',true,true);" +
" l.dispatchEvent(e);" +
"})()");
} catch (InterruptedException e) {
e.printStackTrace();
}
It's because the page is not loaded yet when you are trying to query the DOM. You need to query the DOM when you can be sure that the page has loaded.
We need to set the WebViewClient for the webview and then listen to onPageFinished event. The code might look something like this:
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// you can now query the DOM.
webView.loadUrl("javascript:var a = document.getElementById('imgCaptcha').src;");
}
});
Further reading: https://developer.android.com/reference/android/webkit/WebViewClient#onPageFinished(android.webkit.WebView,%2520java.lang.String)
Related
Here's my code for injecting CSS into a Webview:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Ubqari");
ww = (WebView) findViewById(R.id.ww);
ww.getSettings().setJavaScriptEnabled(true);
ww.getSettings().setDomStorageEnabled(true);
ww.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url) {
injectCSS();
}
});
ww.loadUrl("http://ubqari.org");``
}
And here's injectCSS function:
private void injectCSS() {
try {
InputStream inputStream = getAssets().open("style.css");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
ww.loadUrl("javascript:(function() {" +
"alert('Hello! I am an alert box!');"+
"var parent = document.getElementsByTagName('head').item(0);" +
"var style = document.createElement('style');" +
"style.type = 'text/css';" +
// Tell the browser to BASE64-decode the string into your script !!!
"style.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(style)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
I don't know what's going wrong in this code. My style.css code is correct but the problem is in the onPageFinished section. It's not injecting the CSS when the page has finished loading. Any expert can answer me?
Say, I set my WebView into example.com then I clicked on the page and load the example.com/about.
In the WebView I've injected Javascript to modify the HTML on the example.com, and it worked, and the problem is, how to inject another JavaScript to modify example.com/about. I mean how to inject multiple JavaScript to a multiple page of WebView?
public class MainActivity extends AppCompatActivity {
WebView mWebView;
private int getScale() {
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
Double val = new Double(width) / new Double(100);
val = val * 100d;
return val.intValue();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
mWebView.setWebViewClient(new WebViewClient());
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
// Inject CSS when page is done loading
injectCSS();
mWebView.loadUrl("javascript:var greeting = function (name) {\n" +
" console.log(\"Great to see you,\" + \" \" + name);\n" +
"};");
super.onPageFinished(view, url);
//Inject JS to edit html
injectScriptFile(view, "script.js"); // see below ...
// test if the script was loaded
view.loadUrl("javascript:setTimeout(test(), 500)");
}
private void injectScriptFile(WebView view, String scriptFile) {
InputStream input;
try {
input = getAssets().open(scriptFile);
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close();
// String-ify the script byte-array using BASE64 encoding !!!
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
view.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var script = document.createElement('script');" +
"script.type = 'text/javascript';" +
// Tell the browser to BASE64-decode the string into your script !!!
"script.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(script)" +
"})()");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
mWebView.loadUrl("example.com");
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
}
private void injectCSS() {
try {
InputStream inputStream = getAssets().open("style.css");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
mWebView.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var style = document.createElement('style');" +
"style.type = 'text/css';" +
// Tell the browser to BASE64-decode the string into your script !!!
"style.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(style)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu); // Add menu items, second value is the id, use this in the onCreateOptionsMenu
menu.add(0, 1, 0, "Back");
menu.add(0, 2, 0, "Refresh");
menu.add(0, 3, 0, "Forward");
getMenuInflater().inflate(R.menu.menu_main, menu);
return true; // End of menu configuration
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 3: //If the ID equals 3 , go forward
mWebView.canGoForward();
item.setIcon(R.drawable.forward);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) { // Enables browsing to previous pages with the hardware back button
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { // Check if the key event was the BACK key and if there's history
mWebView.goBack();
return true;
} // If it wasn't the BACK key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
}
Following is the code which is I am implementing:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
webView = (WebView) findViewById(R.id.webTask);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setSaveFormData(false);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
else webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.loadUrl("javascript:document.getElementById('user_id').value='" + new String ("xxx")+ "';javascript:document.getElementById('password').value = '" + new String("xxx") + "';");
}
});
webView.loadUrl(URL);
But nothing happens infact web view turns blank and shows text written on its left corner "xxx"
Please help. already searched 3 to 4 hours and of no avail
At last i have solved the problem. the javascript was not being run because my targeted sdk was >= KITKAT.
So, in order to avoid the problem you have to use webView.evaluateJavascript(yourScript,null); for devices running on API level 19 or above.
Sample Code
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
webView.evaluateJavascript(yourScript,null);
}
else
{
webView.loadUrl(yourScript);
}
In my app one of my Activity is based on a webpage..I want to load a webpage that will display the ExamSeatingPlan from my Student Portal.I am logging into the website using JavaScript and then I want to load the page which will display my ExamSeatingPlan on the same webview. The problem I am facing is when I logged in using javascript the login is successful, but then it's not loading the web page that display my ExamSeatingPlan. It loads the required page if I minimize the app and then after a few second maximize it. I think I didn't implement the onPageFinished correct.It will be very helpful if someone help me solve the problem.
Thanks
MainActivity.java
package com.example.ebad.badwae;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
final String url = "http://111.68.99.8/StudentProfile/";
final String urltesting = "http://111.68.99.8/StudentProfile/ExamSeatingPlan.aspx";
WebView view;
boolean loaded;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (WebView) findViewById(R.id.webview);
WebSettings webSettings = view.getSettings();
webSettings.setJavaScriptEnabled(true);
view.loadUrl(url);
view.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView views, String urls) {
view.loadUrl("javascript: {" + "document.getElementById('ctl00_Body_ENROLLMENTTextBox_tb').value = '" + "01-134121-061" + "';" +
"document.getElementById('ctl00_Body_PasswordTextBox_tb').value = '" + "123456789" + "';" +
"document.getElementsByName('ctl00$Body$LoginButton')[0].click();" + "};");
onPageFinishede(views, urls);
}
public void onPageFinishede(WebView views, String urls) {
if (!loaded) {
views.loadUrl(urltesting);
loaded = true;
}
}
});
}
}
Now It is loading the new page but it is using almost 80% of CPU. Is there any way to reduce the CPU usage?
Try calling the loadotherpage() after your first page finished.
So you need to change the following lines
view.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView views, String urls) {
view.loadUrl("javascript: {" + "document.getElementById('ctl00_Body_ENROLLMENTTextBox_tb').value = '" + "01-134121-061" + "';" +
"document.getElementById('ctl00_Body_PasswordTextBox_tb').value = '" + "123456789" + "';" +
"document.getElementsByName('ctl00$Body$LoginButton')[0].click();" + "};");
}
});
loadotherpage();
to
view.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView views, String urls) {
view.loadUrl("javascript: {" + "document.getElementById('ctl00_Body_ENROLLMENTTextBox_tb').value = '" + "01-134121-061" + "';" +
"document.getElementById('ctl00_Body_PasswordTextBox_tb').value = '" + "123456789" + "';" +
"document.getElementsByName('ctl00$Body$LoginButton')[0].click();" + "};");
if(!loaded){
loadotherpage();
loaded = true;
}
}
});
I'm making some sort of book reader in webView. I have used the JavaScript, which dynamically creates the <img> tags via for loop. Look at the code's for loop, and every img tag is loaded with a different image from the URL.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView) findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
progressDialog = ProgressDialog.show(MainActivity.this,
"Loading Book...!", "Please Wait");
String htnlString = "<!DOCTYPE html><html><body style = \"text-align:center\"><script>var out = '';for (var counter = 1; counter <= 100; counter++){ out += '<img src=\"http://shiaislamicbooks.com/books_snaps/UR335/'+counter+'.jpg\"alt=\"Page No:'+counter+'\" width=\"100%\" />';}document.write(out);</script></body></html>";
wv.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Completed",
Toast.LENGTH_SHORT).show();
super.onPageFinished(view, url);
}
});
wv.loadDataWithBaseURL(null, htnlString, "text/html", "UTF-8", null);
}
Look at the htnlString:
Now I want to display a book pages information in a textView. This means, while scrolling the webview the textView should update the txtPage.
the scrollTo(x,y) is some how useful but I want the scroll listener for the webview.
WebView webview;
yPos = webview.getScrollY();
xPos=webview.getScrollX();