get the click event from webpage in my Android application - java

I'm creating a sample webpage with button..this webpage am calling in Android using webview.
now when I click the button on webpage(that is html button). I should be able to execute some codes in Android..
How to proceed?
public class web extends Activity {
WebView mWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webdisplay);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://localhost/test.html");
valid = new Button(ctx);
valid.setOnClickListener(this);
refuse = new Button(ctx);
refuse.setOnClickListener(this);
}
}

We can detect following HTML elements as per Android API Document.
int ANCHOR_TYPE HitTestResult for hitting a HTML::a tag
int EDIT_TEXT_TYPE HitTestResult for hitting an edit text area
int EMAIL_TYPE HitTestResult for hitting an email address
int GEO_TYPE HitTestResult for hitting a map address
int IMAGE_ANCHOR_TYPE HitTestResult for hitting a HTML::a tag which contains HTML::img
int IMAGE_TYPE HitTestResult for hitting an HTML::img tag
int PHONE_TYPE HitTestResult for hitting a phone number
int SRC_ANCHOR_TYPE HitTestResult for hitting a HTML::a tag with src=http
int SRC_IMAGE_ANCHOR_TYPE HitTestResult for hitting a HTML::a tag with src=http + HTML::img
int UNKNOWN_TYPE Default HitTestResult, where the target is unknown
I think you will be able to get all events using WebView's setOnTouchListener function.
WebView has inner class named HitTestResult.
HitTestResult class will help us to find the HTML element which press when user click on WebView.
HitTestResult class has only two method.
getExtra() : It return String. String has HTML element which is clicked by user
getType() : It return integer. It is used to identify which HTML element is clicked by user.
You can do like :
wv.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
WebView.HitTestResult hr = ((WebView)v).getHitTestResult();
Log.i(TAG, "getExtra = "+ hr.getExtra() + "\t\t Type=" + hr.getType());
return false;
}
});
Edited :
Refer for perfect answer :
Detect click on HTML button through javascript in Android WebView

Related

programmatically click on a HTML button in WebView from fragment in Android

I need to open a dialog in a website which opens on clicking a HTML button of the website. I'm trying to click on a HTML button based on the id from the fragment, how can I perform the action, I'm using
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// trying to click the button with id btn-to-be-clicked
webView.loadUrl("javascript:(function(){document.getElementById('btn-to-be-clicked').click();})()");
}
}
thanks
I tried
webView.loadUrl("javascript:(function(){document.getElementById('btn-to-be-clicked').click();})()");
so apparently you must specify every line in a new string
extracted the js to a variable with multi line, it has to be a multi line concatenated string
val jsFunction = "javascript:(function() { " +
"document.getElementById('btn-to-be-clicked').click();" +
"})()"

Get random Youtube video in webview by clicking button in Android studio

I want to make an app where the user can get random youtube videos in a webview by clicking a button.
I already can show a video in my webview with the url but I want to get any random video from youtube by clicking my button.
In my xml file I have a webview and a button
´´´
MainActivity.java
´´´
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String path = "https://www.youtube.com/watch?v=1uwvxTT5V5M";
String dataUrl =
"<html><body>Video From YouTube<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/47yJ2XCRLZs\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
WebView showYoutubeVideo = (WebView) findViewById(R.id.zufallvideo);
showYoutubeVideo.setWebViewClient(new WebViewClient(){
public boolean shouldoverloadUrlLoading(WebView view, String url) {
return false;
}
});
showYoutubeVideo.getSettings().setJavaScriptEnabled(true);
showYoutubeVideo.loadData(dataUrl,"text/html", "utf-8");
}
}
TL;DR: it's complicated.
Until Youtube exposes an endpoint in their API to do this, you're gonna need to find a workaround.
Some would suggest to query a search with "IMG" followed by a random integer (ex. "IMG 22930"). The end result is quite surprising, since tons of videos are uploaded without renaming.
Here's an example of this workaround implementation in python: https://github.com/0x01h/random-youtube-video-generator

How to open html string "a href" to Webview?

how can i open the html string that has a href on webview only instead of going on your browser?
i am using the LinkMovementMethod, this is okay on opening it on other app like video from youtube but i have some links that needs to be open only on webview.
here is a sample html string
String html_text = "<h1>sample text</h1><p><small>February 1 1970</small></p><p class=\"text-center\"><img src=\"https://www.google.com\" /></p><p>sample (here).</p>"
i need the a href to be open only on webview.
here is my code
DetailActivity
public class DetailActivity extends AppCompatActivity implements Html.ImageGetter {
private TextView newsContentTv;
private WebView newsWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_news);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
newsWebView = (WebView) findViewById(R.id.newsWebView);
setSupportActionBar(toolbar);
// add back arrow to toolbar
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
newsContentTv = (TextView) findViewById(R.id.textNewsContext);
Intent i = getIntent();
String news_content = i.getStringExtra("detail_content");
Spanned spanned = Html.fromHtml(news_content, this, null);
Spannable spannable = new SpannableString( Html.fromHtml(news_content) );
newsContentTv.setText(spanned);
newsContentTv.setMovementMethod(LinkMovementMethod.getInstance());
}
any help would be really appreciated.
// Create an unencoded HTML string
// then convert the unencoded HTML string into bytes, encode
// it with Base64, and load the data.
String html_text =
"<h1>sample text</h1><p><small>February 1 1970</small></p><p class=\"text-center\"><img src=\"https://www.google.com\" /></p><p>sample (here).</p>";
String encodedHtml = Base64.encodeToString(html_text.getBytes(),
Base64.NO_PADDING);
newsWebView.loadData(encodedHtml, "text/html", "base64");
I hope this will help you.
WebView webview = (WebView)this.findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadDataWithBaseURL("", data, "text/html", "UTF-8", "");
Your question states you need to open the clicked url in your webview instead of navigating to browser. I can think of two ways to do this.
First case, if its not necessary to have a Textview to display the clickable link then you can load your string into the WebView itself (as others mentioned) and set a WebViewClient (this part is important)
newsWebView.loadDataWithBaseURL(null, html_text, "text/html", "UTF-8", null);
newsWebView.setWebViewClient(new WebViewClient());
// add below line to support youtube videos etc.
newsWebView.getSettings().setJavaScriptEnabled(true);
newsWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
so that any click keeps the navigation in the same WebView. Without the client it will navigate to the browser. But you should note this will load and replace the content inside, so your original link will not be there on screen.
Second case, if you need the clicks to be from the TextView simply setting newsContentTv.setMovementMethod(LinkMovementMethod.getInstance()); won't work as by default it will make the normal intent causing it to navigate to browser or related apps, you need to remove that. Then, you have to create a custom class extending LinkMovementMethod and override the touch event to load the url clicked into your webview as shown below:
public class CustomLinkMovementMethod extends LinkMovementMethod {
private static CustomLinkMovementMethod instance;
public static CustomLinkMovementMethod getInstance() {
if (instance == null)
instance = new CustomLinkMovementMethod();
return instance;
}
#Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_UP) {
int x = (int) event.getX() - widget.getTotalPaddingLeft() + widget.getScrollX();
int y = (int) event.getY() - widget.getTotalPaddingTop() + widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
URLSpan[] urlSpans = buffer.getSpans(off, off, URLSpan.class);
if (urlSpans.length != 0) {
// You can check log to see if you are getting the url on click.
Log.d("TAG", String.valueOf(urlSpans[0].getURL()));
/* If you've made this an inner class in your activity
you can directly load the url into your webview.
Else you will have to create listeners to get url in activity
on event trigger */
newsWebView.loadData(urlSpans[0].getURL());
return true;
}
}
return super.onTouchEvent(widget, buffer, event);
}
}
use this on the TextView like
newsContentTv.setMovementMethod(CustomLinkMovementMethod.getInstance());
See if this works for you, hadn't expected the answer to become this long.

Send to Messenger Button not showing up in Android Webview

Context: I'm trying to link an authenticated user in my android app to a Facebook fanpage PSID using the "Send to Messenger" Plugin to be able to send messages to that specific user on certain events that responds to the user actions in other systems.
I figured the best way to achieve this (since said plugin only works with the Facebook Javascript SDK) was to open a WebView Activity in my app, loading a website with the plugin button.
The website includes the following to load the SDK and the button:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<<Here I put my FB App ID>>',
autoLogAppEvents : true,
xfbml : true,
version : 'v2.12'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div class="fb-send-to-messenger"
messenger_app_id="<<Same FB App ID>>"
page_id="<<FB fanpage ID>>"
data-ref="<<user identification>>"
color="blue"
size="standard">
</div>
Here's the onCreate method of the Webview Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(webview);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
webview.getSettings().setJavaScriptEnabled(true);
final Activity activity = this;
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
activity.setProgress(progress * 1000);
}
#Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.d("WEBVIEW_CONSOLE", consoleMessage.message() + " -- From line "
+ consoleMessage.lineNumber() + " of "
+ consoleMessage.sourceId());
return super.onConsoleMessage(consoleMessage);
}
});
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl(getString(R.string.authenticated_webview_url_example), headers);
Expectation: The facebook Send to Messenger Button should load in the WebView, allowing the user to register a PSID on my Facebook fanpage/App.
Problem: When I load the website on the Android WebView, the button is not shown.
Details: Using Chrome Remote Debugging, I was able to determine the Facebook SDK was working and almost all the elements of the buttons were loaded, except for the content of the iframe generated.
Tested the Facebook jssdk by using a Like button, which worked and was shown.
No errors in website console or logcat.
Why is WebView not showing that particular button?
Testing website: https://www.vsdesigns.cl/debug/login.php
Edit:
Here is an image of the testing website from a desktop browser. It shows the button.
Here is another image with the testing website being loaded by the WebView. It's actually a representation of the chrome remote debugger, but it's the same as what my smartphone screen shows. It doesn't show the button.
Thanks in advance.
I figured out the Facebook Cookies weren't loading at all, and Facebook doesn't render the plugin if the App is in development and the user is not previously logged in, so I implemented the following code to accept Third party cookies. (Only works on SDK version 21 Lollipop and up)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.setAcceptThirdPartyCookies(mWebview,true);
}
mWebview would be the variable storing the actual WebView.

How to get text of hyperlink of webview once click in android?

I am building an android application where a URL is loaded on a webView. Now in that URL, there are some Hyperlink's which is loaded when a user clicks on them. While click I get that URL string and a load that URL in webView.
Now I need when a user clicks on that Hyperlink I need to get that text of that Hyperlink. I had to google a lot yet did not get any good answers.
This function will show all resources text(hyperlink, image, css file, js file)
webView.setWebViewClient(new WebViewClient(){
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
Log.d(TAG, "onLoadResource: " + url);
}
});
So you have to check before using it
if (!url.endsWith(".css")
&& !url.endsWith(".js")
&& !url.endsWith(".otherformat") ) {
// Show your url
}

Categories