Android String to WebView with Javascript - javascript

I am trying to get Intent data to the loaded WebView.
Before the intent, There was a EditText, and I originally used the values to login to myURL site with the WebView inside that Activity whitch had userID and userPW (at the site).
But for better design, I've move the Webview to another activity and sends the ID,PW with Bundle.
The problem is that the String variable email and password seems to be set well, but when i try to use the same code i used before, it doesn't work well.
Is there some rules in Android that i can't pass the variables directly without user input? Does someone know how to solve this problem?
Below is the code i'm currently stuck on
public class MyWeb extends Activity{
WebView webview;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_myweb);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
email = bundle.getString("ID");
password = bundle.getString("PW");
webview = (WebView)findViewById(R.id.logIn);
webview.setWebViewClient(new WebClient());
webview.getSettings().setDatabaseEnabled(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("myURL");
login(email, password);
}
private void login(String id, String pw){
webview.loadUrl("javascript: {" +
"document.getElementById('userID').value = '"+email +"';" +
"document.getElementById('userPW').value = '"+password+"';" +
"var a = document.getElementsByTagName('input');" +
"a[2].CheckSubmit(); };");
webview.loadUrl("javascript:CheckSubmit()");
}

webview.setWebViewClient(new WebClient() {
#Override
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript: {" +
"document.getElementById('userID').value = '" + email + "';" +
"document.getElementById('userPW').value = '" + password + "';" +
"var a = document.getElementsByTagName('input');" +
"a[2].CheckSubmit(); };");
webview.loadUrl("javascript:CheckSubmit()");
}
});
Solved, I guess it was because of the JS was called before the webpage load thinking that the Activity before this loads all the page while i type in the fields

Related

Get an image src from a webview in android

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)

Using Javascript in android WebView to call a function

Background:-
I am trying to call a #JavascriptInterface annotated method processVideo() form the loadUrl() of webview to get callback when someone click on any video on the webpage.
The following is my approach and it's working perfectly
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
webView = findViewById(R.id.web_view_facebook);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.addJavascriptInterface(this, "Downloader");
webView.setWebViewClient(new WebViewClient() {
#Override
public void onLoadResource(WebView view, String url) {
webView.loadUrl("javascript:(function prepareVideo() { "
+ "var el = document.querySelectorAll('div[data-sigil]');"
+ "for(var i=0;i<el.length; i++)"
+ "{"
+ "var sigil = el[i].dataset.sigil;"
+ "if(sigil.indexOf('inlineVideo') > -1){"
+ "delete el[i].dataset.sigil;"
+ "console.log(i);"
+ "var jsonData = JSON.parse(el[i].dataset.store);"
+ "el[i].addEventListener('click',function(){Downloader.processVideo(jsonData['src'],jsonData['videoID']);});"
+ "}" + "}" + "})()");
}
});
webView.loadUrl("https://m.facebook.com");
}
#JavascriptInterface
public void processVideo(final String vidData, final String vidID) {
try {
Toast.makeText(this, "Download Started", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Download Failed: " + e.toString(), Toast.LENGTH_LONG).show();
}
}}
Now The Problem:-
But as i load custom javascript function in loadUrl(), i lost the ability to play video on click.
i think it will happen as i intercepted and load my custom code
So what i want to achieve is when any user click on video, then the video should play and also i get the callback that i wanted at first place
What i have tried so far:-
to play the video on click, i used
addEventListener('click',function(){
var video = document.getElementById(jsonData['videoID']);
video.play(); }
This one is working perfectly to play the video.
but when i use this solution with my callback like following
addEventListener('click',function(){
Downloader.processVideo(jsonData['src'],jsonData['videoID']);
var video = document.getElementById(jsonData['videoID']);
video.play(); }
then I am not able to get callback in my processVideo().
If i use them individually, both functionality (callback and play video) working perfectly inside addEventListener(), but not working together.
This code line: var video = document.getElementById('jsonData['videoID']') throws an error because you used more than two 's in one argument.
Try replacing by var video = document.getElementById(jsonData['videoID']).
Hope this helps.
I have solved this issue and i am pasting complete code here:
webView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
//query_string = "" + url;
// view.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()");
}
#Override
public void onLoadResource(WebView view, String url)
{
// query_string=""+url;
webView.loadUrl("javascript:(function prepareVideo() " +
"{ "
+ "var el = document.querySelectorAll('div[data-sigil]');"
+"var ID;"
+"var SRC;"
+ "for(var i=0;i<el.length; i++)"
+ "{"
+ "var sigil = el[i].dataset.sigil;"
+ "if(sigil.indexOf('inlineVideo') > -1)" +
"{"
+ "delete el[i].dataset.sigil;"
+ "console.log(i);"
+ "var jsonData = JSON.parse(el[i].dataset.store);"
+"ID=jsonData['videoID'];"
+"SRC=jsonData['src'];"
// +"document.getElementsByTagName(\"'+jsonData['videoID']+'\")[0].play();"
+ "el[i].setAttribute('onClick','FBDownloader.processVideo(\"'+jsonData['src']+'\",\"'+jsonData['videoID']+'\");');"
+ "}"
+ "}"
+ "})()");
}
});
JAVA ACTIVITY FUNCTION WHICH IS CALL FROM JAVASCRIPT WEBVIEW
public void processVideo(final String vidData, final String vidID)
{
this.vidData=vidData;
this.vidID=vidID;
Get_Download_Permission();
showtoast("video ID ="+this.vidID);
webView.loadUrl("https://www.facebook.com/video/embed?video_id="+this.vidID);//193766537709747/");
}

Webview is not loading two page

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;
}
}
});

Calling JS function from Android Activity

I am calling a simple JS function to set values of some html contents, but its not working
Here is the JS function
function SetEdits(name,email,pic,date)
{
document.getElementById("myPic").src=pic;
document.getElementById("fullname").value=name;
document.getElementById("email").value=email;
}
and here is the code from android activity
edit.loadUrl("edit.html");
edit.loadUrl("javascript:SetEdits('"+name+"','"+email+"','"+picture+"','"+date+"')");
its not settings these fileds.. is there any problem with the synax where i am calling this function in native activity?
You're probably ending up evaluating the JavaScript before the "edit.html" page has loaded. Try this:
// I'm assuming the real path is something like file:///android_asset/edit.html
edit.loadUrl("edit.html");
edit.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (Uri.parse(url).getPath() == "edit.html") {
view.loadUrl("javascript:SetEdits('" + name+"','" + email + "','" +
picture + "','" + date + "')");
}
}
Have you enabled the javascript for the webview ?
You have to setup a javascript interface between your app and html.
Here is some details Webapp guid

Android WebView

With reference to this WebView tutorial, in particular this method
private void setupWebView(){
String MAP_URL = "http://gmaps-samples.googlecode.com/svn/trunk/articles-android-webmap/simple-android-map.html";
String centerURL = "javascript:centerAt(" + mostRecentLocation.getLatitude() + ","+ mostRecentLocation.getLongitude()+ ")";
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
//Wait for the page to load then send the location information
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url){
webView.loadUrl(centerURL);
}
});
webView.loadUrl(MAP_URL);
}
I've noticed that if I place the webView.loadUrl(centerURL); directly after
webView.loadUrl(MAP_URL); like this
private void setupWebView(){
String MAP_URL = "http://gmaps-samples.googlecode.com/svn/trunk/articles-android-webmap/simple-android-map.html";
String centerURL = "javascript:centerAt(" + mostRecentLocation.getLatitude() + "," + mostRecentLocation.getLongitude()+ ")";
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
//Wait for the page to load then send the location information
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url){
//DO NOTHING
}
});
webView.loadUrl(MAP_URL);
webView.loadUrl(centerURL);
}
it no longer works. So the centreAt(..) javascript method is contained int the MAP_URL.
I'm wondering if the webView.loadUrl(..) method returns before the url has actually been loaded.
It looks that way since the top method waits for it to load fully before running the javascript
Yes, webView.loadUrl() is asynchronous: it returns immediately and WebView keeps working in it's own thread.
To monitor WebView page loading use WebViewClient.onPageFinished(..):
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do something here
}
});

Categories

Resources