I am new to the webView concept in Android development, I have used a website url for the webView in my app which works like when you open the app the app will directly show the webView, the website's login page will be the first page that opens up in the webView and then user will be directed to the next page of the website eventually after logging in succesfully, Now I want to save the user's ID and password so that the next time the user opens my app he/she should be taken to the main page of the website in the webView without logging in again and again. Please help me finding the solution for this......
I am not able to figure out how can I save the details or save the response in a webView
if you want to save credentials from a WebView to your app, you can do so by implementing a WebViewClient and intercepting the login form submission.
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
// Find the login form fields and submit button
val js = """
var username = document.querySelector('#username');
var password = document.querySelector('#password');
var submit = document.querySelector('#submit');
[username.value, password.value];
""".trimIndent()
webView.evaluateJavascript(js) { result ->
// The result is a JSON-encoded array of the username and password
val credentials = JSONArray(result)
val username = credentials.getString(0)
val password = credentials.getString(1)
// Save the credentials to secure storage (e.g. Android Keystore)
// ...
}
}
}
Related
I've an App, in which there is WebView. When I try to open any Universal link/Deep Link available on the web page loaded in the WebView it should open the targeted app but it open inside the WebView.
and yes I've implemented the shouldOverrideUrlLoading like below from WebViewClient().
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest):
Boolean {
view.loadUrl(request.uri.toString())
return true
}
The behavior I wanting is if user clicks on any normal URL it should open inside WebView and if there is any Universal Link or any Deep Link, it should open the targeted app like all browser apps are doing.
Any Help will be appreciated.
Thanks
I have found a solution on Android Developer page at this link
and now the shouldOverrideUrlLoading block look like below
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest):Boolean {
val url = request.url.toString()
try {
val intent = Intent(ACTION_VIEW, Uri.parse(url)).apply {
// The URL should either launch directly in a non-browser app (if it's
// the default), or in the disambiguation dialog.
addCategory(CATEGORY_BROWSABLE)
flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_REQUIRE_NON_BROWSER
}
startActivity(intent)
} catch (e: ActivityNotFoundException) {
// Only browser apps are available, or a browser is the default.
// So you can open the URL directly in your app, for example in a
view.loadUrl(url)
}
return true
}
Hope this will helpful for other...
Only after visiting almost all Stack Overflow links for the same answer, I was compelled to write this,
I am trying to display a PDF file in the WebView. I am aware that WebView doesn't support displaying PDF normally so I am using the G-Drive URL extension suggested in other answers. Also, the Business team has demanded to open the PDF in our App itself so I can't fire an Intent to other PDF Viewer. I downloaded the PdfViewer library but it increased the APK size far beyond desire.
This URL is actually a GET request. Every time I hit the request, depending on the request parameters the server generates the PDF at runtime and returns it immediately without storing it on the server.
PDF URL:
"http://server_ip_number/pata/retail/v4/reports_pdf?search=Test&min_amount=0.0&max_amount=0.0" (can't disclose IP address for security reasons)
This request also demands some headers for auth, which I'll post below in detail.
This is what I am doing currently;
class AllUsersWebViewActivity : BaseActivity() {
private val pdfActualUrl = "https://drive.google.com/viewerng/viewer?embedded=true&url=http://server_ip_number/pata/retail/v4/reports_pdf?search=Test&min_amount=0.0&max_amount=0.0"
//This random dummy URL opens perfectly, it does not need any headers or GET params, just normal `loadUrl()` works.
private val workingDummyUrl = "https://drive.google.com/viewerng/viewer?embedded=true&url=https://mindorks.s3.ap-south-1.amazonaws.com/courses/MindOrks_Android_Online_Professional_Course-Syllabus.pdf"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_all_users_report_web_view)
wv_web.settings.javaScriptEnabled = true
wv_web.clearCache(true)
wv_web.loadUrl(URLEncoder.encode(pdfUrl, "ISO-8859-1"), mapOf( //map of necessary headers
"Authorization" to "Auth_TOKEN",
"VersionId" to "1.0.0",
"companyID" to "2",
"DeviceId" to "my_device_id",
"token" to "SECURE_TOKEN"
))
}
NOTE:
When I hit the above mentioned GET request with headers and params on PostMan it immediately downloads the PDF file.
I tried the same GET request with DownloadManager with all the headers and params the PDF file is downloaded successfully
But when I try it with WebView it just shows No Preview Available.
What am I doing wrong?
The headers that you are supplying, at most, will affect the behavior of Google's Web server for the https://drive.google.com/viewerng/viewer request. Google is not going to pass those along to some other server for http://server_ip_number/pata/retail/v4/reports_pdf.
I created a Webview android app for my website so as to have an android version of my website. The website allows a user to sign in before proceeding to the website information.
Please, How do I fetch the user signed in details (e.g email) from the website in my Webview android app?
You can get the content of the WebView using this function:
yourWebView.evaluateJavascript(
"(function() { return ('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>'); })();",
new ValueCallback<String>() {
#Override
public void onReceiveValue(String html) {
Log.d("HTML", html);
// Here you work with the content of the page which is stored in the 'html' variable
}
});
Since you are able to read the content of the page, you can either hide the data you want to read in the website in a hidden field (e.g. <input type="hidden" id="emailAddress" name="emailAddress" value="someone#example.org">).
Or you can create a own Activity where the use can insert his email address, and then you can post the inserted email address on your website using the WebView.postUrl(String url, byte[] postData) function (e.g. webView.postUrl("https://yourWebsite.com/index.php", "emailAddress=someone#example.org".getBytes());).
Source:
https://developer.android.com/reference/android/webkit/WebView.html
how to get html content from a webview?
How to post data for WebView android
Never really worked with OAuth, trying to implement it now, I want to get access token and profile data from google and facebook. Using Xamarin.Auth.
With Facebook there're no problems, I specify "http://www.facebook.com/connect/login_success.html" as redirect url and after I login it goes back to the activity I was before.
However with Google it's not as smooth - couldn't find any similar to facebook login success pages, somewhere found suggestion to use "https://www.googleapis.com/plus/v1/people/me" - added it to redirect url white list, however after sign in I would get "Redirect_url_mismatch" A native application: application nameaccording to their documentation I should use "my.package.name:" and again I added that to redirect url white list, attempted to sign in, this time after sign in screen I get to second screen where I need to confirm read permissions and after that I get very short error something like "com.my.package:/?oauthparameterX=value1...." and get redirected to permission screen again.
Here's my complete OAuth2Authenticator:
var auth = new OAuth2Authenticator(
clientId: SocialIds.GooglePlusId,
clientSecret: SocialIds.GooglePlusSecret,
scope: OAuthUrl.GoogleScope,
authorizeUrl: new Uri(OAuthUrl.GoogleAuthorize),
redirectUrl: new Uri("https://www.googleapis.com/plus/v1/people/me"),
accessTokenUrl: new Uri("https://accounts.google.com/o/oauth2/token"),
getUsernameAsync: null);
auth.AllowCancel = false;
urls:
public static string GoogleAuthorize = "https://accounts.google.com/o/oauth2/auth";
public static string GoogleScope = "https://www.googleapis.com/auth/userinfo.email";
public static string GoogleRedirect = "https://www.googleapis.com/plus/v1/people/me";
public static string GoogleUserInfo = "https://www.googleapis.com/oauth2/v1/userinfo?access_token={0}";
In the above listed code, you are not giving the redirect uri instead you are giving the scope of google api. The purpose of redirect uri is to recieve the response from google api after authorization. The response should be a code. This response code is used for accessing the access_token,refresh_token, id_token etc. So you have to recieve this code in your project side.For this purpose , the redirect uri is used.
Go to your google console, create project, add credentials, then you will be redirect to a page conatains,
You can find the authorized redirect url. Give the url , then configure your code with new redirect url . Everything will be fine after this.
I am developing an Android app in which I need to get the information from a website that requires login credentials.
After login it will display the home page, then clicking a button will direct it to the data page.
I am getting the HTML of the login page and sending the user ID and password to it. It is successful and I am getting the HTML code of the home page, and now I am making another request for the useful data.
I am passing the cookie information along with the URL but it is redirecting to login page. Am I missing any other vital Information that I need to pass?
// Login code
Connection connection = Jsoup.connect(url).method(Method.GET);
Response response = connection.execute();
cookies = response.cookies();
doc = response.parse();
Element viewstateNode = doc.getElementById("__VIEWSTATE");
Element eventvalidationNode = doc.getElementById("__EVENTVALIDATION");
String viewStateValue = viewstateNode.attr("value");
String eventValidationValue = eventvalidationNode.attr("value");
connection = Jsoup.connect(url)
.data("__VIEWSTATE", viewStateValue)
.data("__EVENTVALIDATION", eventValidationValue)
.data("txtLoginID", username)
.data("txtPWD", password)
.data("btnLogin", "Go%21")
.followRedirects(true)
.userAgent("Google")
.cookies(cookies)
.maxBodySize(100000)
.timeout(60000);
response = connection.method(Method.POST).execute();
doc = response.parse();
// Doc contains the HTML code of next page after successful login. Now I need to get the HTML code of next page with useful data.
// I am using the following code to make the second request.
Connection connection = Jsoup.connect(url_datapage)
.cookies(cookies)
.userAgent("Google")
.maxBodySize(100000)
.timeout(60000)
.method(Method.GET);
Response response = connection.execute();
doc = response.parse();
But doc contain the HTML code of login page. It is redirecting to home page again.