How to close webview in mobile android/iOs(Native app) - javascript

In our app have opening one url in webview there is way to close webview after some specific url detect.
how can possible to close webview ? I have try with window.close() in javascript.but could not work.have another way from android or ios app.

As per comments on question, I am putting a better term for closing the web view - going back to previous screen. You can do this as follows for Android and iOS :
Android :
finish()
iOS :
If you are using navigation controller :
self.navigationController?.popViewController(animated: true)
If you are presenting web view controller :
self.dismiss(animated: true, completion: nil)
The key is to check that url in the delegate function of web view.
Android :
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.equals("your_url")) {
finish()
return false;
} else {
return true;
}
}
iOS :
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.url?.absoluteString == "your_url" {
self.navigationController?.popViewController(animated: true)
// If controller is presented - self.dismiss(animated: true, completion: nil)
return false
}
return true
}

You can use shouldOverrideUrlLoading
Give the host application a chance to take over the control when a new url is about to be loaded in the current WebView. If WebViewClient is not provided, by default WebView will ask Activity Manager to choose the proper handler for the url. If WebViewClient is provided, return true means the host application handles the url, while return false means the current WebView handles the url.
Notes:
This method is not called for requests using the POST "method".
This method is also called for subframes with non-http schemes, thus it is strongly disadvised to unconditionally call loadUrl(String) with the request's url from inside the method and then return true, as this will make WebView to attempt loading a non-http url, and thus fail.
Here is the sample demo
public class MainActivity extends AppCompatActivity {
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = findViewById(R.id.myWebView);
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("https://stackoverflow.com/users/7666442/nilesh-rathod?tab=topactivity");
}
public class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.equals("https://stackoverflow.com/users/7666442/nilesh-rathod?tab=profile")) {
finish() ;
Toast.makeText(MainActivity.this, "URL DETECTED", Toast.LENGTH_SHORT).show();
// perform your action here
return true;
} else {
view.loadUrl(url);
return true;
}
}
}
}

In iOS you would now be using Safari sfview so directly picking up a URL is blocked for security hence the only universal solution you can apply in both Android and iOS apps is deep linking.
You can trigger to close the safari sf view when you reach that specific URL using deep link.
Google deep link and follow the examples.

Use this can help you
myWebView.destroy();
myWebView = null;

Related

opening link in external browser from page in WebView

I'm developing an angular website which is loading in an app from a WebView, and there is only one of the links in it that has to be opened outside of the app (external browser)
I need a way to handle this from JavaScript not putting extra work to the android side.
and i have already tried some ways including:
window.open("url","_system")
(navigator as any).app.loadUrl("http://google.com", {openExternal : true});
Well, there is no such thing
instead it must be handled from android application code. you can add a parameter to the url when u need it to open in external browser, ( here it is external=true ) and then check for that parameter in your webview url loading as below:
webView.setWebViewClient(new WebViewClient(){
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if((String.valueOf(request.getUrl())).contains("external=true")) {
Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
view.getContext().startActivity(intent);
return true;
} else {
view.loadUrl(String.valueOf(request.getUrl()));
}
return true;
}
});

Blank page when trying to do a facebook login inside an android webview app

I developed an android webview application, and everything is workong fine. But inside the website you can login via a facebook button, which is working in all browsers, but not inside the webview app. Just when I click the facebook login button a blank page appears.
Others have quite similar problems like me, but they can load the facebook page instead of me.
I also tried it with these adds:
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
and
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().setAcceptThirdPartyCookies(myWebView, true);
}
I also want it to open internal, and then redirect automatically to my website's login page.
EDIT:
Maybe I should also say that the facebook login page opens with a popup and that seems to be a problem.
Try to change the your code same as following
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView htmlWebView = (WebView)findViewById(R.id.webView);
htmlWebView.setWebViewClient(new CustomWebViewClient());
WebSettings webSetting = htmlWebView.getSettings();
webSetting.setJavaScriptEnabled(true);
webSetting.setDisplayZoomControls(true);
htmlWebView.loadUrl("https://inducesmile.com/blog");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class CustomWebViewClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
Try something like below code. You will get error response and you will get to know about the problem.
private void load webPage(){
private WebView mWebview=null ;
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), description, Toast.LENGTH_SHORT).show();
}
});
mWebview.loadUrl("YOUR URL");
setContentView(mWebview );
}
}
We just changed the facebook login site, it wont now appear inside a pop-up. Bute theres is still a small problem, afte you login in facebook it brings you back to the main login site. It seems that the login wasnt successfull, but it is. you have to go to the main site for example to see that you are logged in. Maybe someone knows why?

Android Webview : How to catch click on the given local URL

I displaying the content in the webview. Content is loaded from the server API. Content can contain following links:
Register
How can i catch click on the #register.
I can do it with some HTML parser and append onClick event, but much better and easier will be to catch URL change to #register.
Many thanks for any advice.
Edit:
I tried the following example but without the luck
browser = (WebView) view.findViewById(R.id.intro_browser);
// Set Chrome instead of the standard WebView
browser.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
Logger.d("TEST");
return true;
}
#Override
public void onLoadResource(WebView view, String url) {
Logger.d("URL IS:");
Logger.d(url);
if (url.startsWith("app://")) {
}
}
});
browser.getSettings().setJavaScriptEnabled(true);
browser.addJavascriptInterface(new WebViewJavaScriptInterface(getContext()),
Constants.Welcome.JAVASCRIPT_NAMESPACE);
//browser.getSettings().setAllowFileAccessFromFileURLs(true);
//browser.getSettings().setAllowUniversalAccessFromFileURLs(true);
browser.loadData(htmlContent, Constants.Welcome.MIME_TYPE, Constants.Welcome.ENCODING);
You need to create custom WebViewClient:
public class CustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean result = false;
if (Objects.equal(url, "#register")) {
result = true;
//Do what you want here
}
return result;
}
}
and then you need to give it to WebView:
webView.setWebViewClient(new CustomWebViewClient());
returning true in shouldOverrideUrlLoading means that you handled the Url while returning false means that WebView should handle it.
Add an intent filter in your manifest so that links starting with "yourapp://" or something similar will launch your app.
If you are generating the web content, then generate links for your app.
Register
If you are not generating the content, then use webview.load("javascript:// code to replace register links to yourapp://").

Unable to execute Js code in WebView in Cordova Project

I have two activity, one main activity(A) is an CordovaActivity, then I use intent to start another activity(B), in B i have an WebView(not CordovaActivity), and after I use this webview to load a simple webpage (alert something), I found the js code is not executed at all, even if I enable javascript by calling setttings.setJsenabel(true);
I start activity B from A
Load Url from webview in Activity B
simple web page
in the device, it does not alert anything
However, if I change the webview to CordovaWebView instead of the original Android native one, it works.....
That's because plain WebView doesn't support showing alerts by itself. You need to provide a WebChromeClient to it that implements WebChromeClient.onJsAlert method. For example:
mywebView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(
WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(view.getContext())
.setTitle("Alert")
.setMessage(message)
.setPositiveButton("Ok",
new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
});

shouldoverrideurlloading not called Webview Android

First of all , this post may ,look like a Possible Duplicate of other question, but I have go through many questions but found them not helpful.
Now My problem is that I am loading an URL in my Webview and then I want to Trace URL on each event on webview so I have set up WebviewClient for Webview and overridden shouldoverrideurlloading method, but after first Event , shouldoverrideurlloading not getting called. (worked first time)
Here is the Code I have used :
wvSecurity = (WebView) findViewById(R.id.wvSecurity);
wvSecurity.getSettings().setJavaScriptEnabled(true);
wvSecurity.getSettings().setAllowContentAccess(true);
wvSecurity.getSettings().setAllowUniversalAccessFromFileURLs(true);
wvSecurity.getSettings().setBuiltInZoomControls(false);
wvSecurity.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wvSecurity.getSettings().setLoadWithOverviewMode(true);
wvSecurity.getSettings().setDomStorageEnabled(true);
wvSecurity.loadUrl("URL");
wvSecurity.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view,
final String urlStr) {
Log.i("URL", "::" + urlStr);
return false;
}
}
EDIT ::
Ok, The URL which I want to Trace uses POST method , Now my question is How can I trace POST URL and its data. And one thing , I dont have access to Webpage coming in so I simply cant go for GET method. Please Help !!!
I guess this method gets called when a hyperlink is tapped from page or some redirection happens. So make sure this thing.
I think you need to pass the url in place on "URL" so this will solve your problem.
wvSecurity = (WebView) findViewById(R.id.wvSecurity);
wvSecurity.getSettings().setJavaScriptEnabled(true);
wvSecurity.getSettings().setAllowContentAccess(true);
wvSecurity.getSettings().setAllowUniversalAccessFromFileURLs(true);
wvSecurity.getSettings().setBuiltInZoomControls(false);
wvSecurity.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wvSecurity.getSettings().setLoadWithOverviewMode(true);
wvSecurity.getSettings().setDomStorageEnabled(true);
wvSecurity.loadUrl("http://www.google.com");
wvSecurity.setWebViewClient(new HelloWebViewClient());
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("URL :: " + url);
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, final String url) {
}
}

Categories