Is there any way to intercept javascript triggered URL in webview? - javascript

Is there any way to intercept javascript triggered URL in a WebView just like normal hrefs using shouldOverrideUrlLoading()?

onLoadResource() is called when any resource is being called, including JavaScript. The purpose is a bit different though than shouldOverrideUrlLoading().
webControls.setWebViewClient(new WebViewClient() {
//Notify the host application that the WebView will load
//the resource specified by the given url.
#Override
public void onLoadResource (WebView view, String url) {
super.onLoadResource(view, url);
Log.v(TAG, "onLoadResource("+url+");");
}
//Give the host application a chance to take over the
//control when a new url is about to be loaded in the
//current WebView.
#Override
public void shouldOverrideUrlLoading(WebView view, String url) {
super.shouldOverrideUrlLoading(view, url);
Log.v(TAG, "shouldOverrideUrlLoading("+url+");");
}
}

Related

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

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;

How can I get the return value of a JavaScript function called by Android?

Is it possible in Android to call a JavaScript function (which is in my WebView) and get its return value in Java?
I know I can use a JavascriptInterface (in Android), for this I need to call the interface from the js function, but I can't modify the JavaScript function...
So I would like something like below, is it possible?
JavaScript:
function hello(){
return "world";
}
Android:
String res = myWebView.loadUrl("javascript:hello()");
// res = "world"
Thank you
Yes, it is possible. I already do many javascript injection to people website before. You just need to inject your own javascript in any website.
For example
//simple javascript to pass value from javascript to native app
String javascript = "javascript:function testHello(){return Android.hello('HAI'); testHello();}"
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//put your function in string and load the javascript when the page is finished load
view.loadUrl(javascript);
}
});
// 'Android' is your variable key for triggering the function ex: Android.hello(), Android.calculate()
// you can change to other name like 'APP', so in javascript be like this ex: APP.hello(), APP.calculate()
webview.addJavascriptInterface(new WebAppInterface(this), "Android");
//load website
webview.loadUrl(PageUrl);
In WebAppInterface is where you create function to detect the javascript you inject earlier
public class WebAppInterface {
Activity mContext;
public WebAppInterface(Activity c) {
mContext = c;
}
//this function will get your value from the javascript earlier.
//Android.hello('value')
#JavascriptInterface
public void hello(String value){
//you will get HAI message in here
Log.i("TAG",value);
}
}

WebView loads URL 10 times slower than phone's Chrome browser

I've been trying to figure this one out for quite a while, and yet haven't found a solution.
Inside my app I'm extracting a website's HTML through an invisible WebView component. I do not need to view the website, just get the html it loads. The website uses JavaScript to load all of its content, and therefore I need a full web renderer in order to execute that JavaScript. In its current form, I'm overriding the WebViewClient's onPageFinished method to inject JavaScript that dumps the html into a JavaScriptInterface which then processes it.
My main issue here is that when I load this URL inside my app it would take about 8 seconds, whereas loading the exact same URL in the phone's chrome browser it takes less than a second. Any suggestions as to what might be the problem?
If it could be of any help, the JavaScript that gets executed stores a cookie inside the WebView, and then tries to retrieve it, and only if it finds said cookie (which has a short expiration time) it would load the site's HTML. In this case it actually loads data formatted with JSON (about 370k characters).
Relevant WebView code:
private void initWebView(View view) {
class JSInterface{
#JavascriptInterface
public void processHTML(String scheduleJSONResponse){
if(scheduleJSONResponse.length() > 10000){
Log.d(LOG_TAG, "Finished loading JSON");
}
}
}
webView = (WebView) view.findViewById(R.id.fragment_movies_web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JSInterface(), "Android");
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d(LOG_TAG, "Page finished loading");
webView.loadUrl("javascript:window.Android.processHTML(document.getElementsByTagName('html')[0].textContent);");
}
});
webView.loadUrl(url);
}
As for why I check that the length is more than 10k characters: Sometimes onPageFinished would get called more than once, with the first call being before the JavaScript is executed, and so I get HTML containing the script to be executed which isn't what I need.
Thanks in advance for any help!
A logcat to demonstrate the issue:
08-18 22:32:23.623 26238-26238/com.michaelsvit.kolnoa I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#1e4dc08f time:502735009
08-18 22:32:23.638 26238-26238/com.michaelsvit.kolnoa W/cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 26238
08-18 22:32:31.336 26238-26238/com.michaelsvit.kolnoa D/MovieGridFragment: Page finished loading
Current code after simplifying it:
private void initWebView(View view) {
class JSInterface{
#JavascriptInterface
public void processHTML(String scheduleJSONResponse){
if(scheduleJSONResponse.length() > 10000){
Log.d(LOG_TAG, "Finished loading JSON");
}
}
}
webView = (WebView) view.findViewById(R.id.fragment_movies_web_view);
webView.getSettings().setJavaScriptEnabled(true);
//webView.addJavascriptInterface(new JSInterface(), "Android");
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d(LOG_TAG, "Page finished loading");
//webView.loadUrl("javascript:window.Android.processHTML(document.getElementsByTagName('html')[0].textContent);");
}
});
}
through an invisible WebView component..
What when it is visible?
Try it!

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://").

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