How to get URL from long click links in a webview? - android

I want to Create a Context Menu for web view in android. My problem is that I cant get the URL from the clicked link. I write this code for log the clicked link:
webView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
WebView webView1 = (WebView) v;
WebView.HitTestResult hitTestResult = webView1.getHitTestResult();
Log.i("LinkClicked", hitTestResult.getExtra());
return false;
}
});
With this code, when long click on links in websites like stackoverflow, log like this:
https://stackoverflow.com/questions
everything is ok, but when long click on google search results, log like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAJFBMVEVHcEz/AAD/AAD/AAD/AAD/AAD/AAD/AAD/g4P/////KCj/7e0I8rGvAAAAB3RSTlMAT0g5Ggp+EilkVQAAAENJREFUGJVjYCAGsDAzggEzC5jLxo4E2BgYWNlRACsDM5jmggkwMzCBaQ5uqBATTICTk4OAAEILhqEY1mI4DNPphAAASIsES4gsgWgAAAAASUVORK5CYII=
it does not return a link. How I can fix this?

public class MainActivity extends AppCompatActivity {
WebView webView;
String URL1 = "https://stackoverflow.com/questions/60577403/how-to-get-url-from-long-click-links-in-a-webview/60577736?noredirect=1#comment107173847_60577736";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview);
webView.clearHistory();
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
public void onPageFinished(WebView view, String url) {
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
URL1 = url;
return super.shouldOverrideUrlLoading(view, url);
}
});
webView.loadUrl(URL1);
// Register the context menu for web view
registerForContextMenu(webView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// Get the web view hit test result
final WebView.HitTestResult result = webView.getHitTestResult();
// If user long press on url
if (result.getType() == WebView.HitTestResult.ANCHOR_TYPE ||
result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
// Set the title for context menu
menu.setHeaderTitle("\t\t\t\t\t\t\t\t\t\t ◦ ◉ ⦿ Select ⦿ ◉ ◦ \t");
// Add an item to the menu
menu.add(0, 1, 0, " \t \t➤\t Show URL")
.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
String Pressed_url = result.getExtra();
Toast.makeText(MainActivity.this, "URL is:-" + Pressed_url,
Toast.LENGTH_SHORT).show();
return false;
}
});
}
}
}
Download Full Code from github.
Output

Related

How to get URL from web view in long click?

I have a web view that I want to get the URL when the user long clicks on links. I know I can do this:
// Register the context menu for web view
registerForContextMenu(webView);
And:
#Override
public void onCreateContextMenu(#NonNull ContextMenu menu, #NonNull View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
final WebView.HitTestResult result = webView.getHitTestResult();
Log.i("url is ===" , "result.getExtra()")
}
But this way, In some search engines like Google, Not be return a URL. This is my log when I long clicked on google search results:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA+klEQVR4AWMgBnwr4pRloAR8KuA89KmAK4V8A/LZ1YGGvPiQy65MtCaQjR8LuDxh/M8FXNlAQ078D2VgJs6APE6rjwWcj4CaOkGaIIZybPucz1FHvCuyeYVBmkBhAArIL6XcEiCvfCzkNMOpCeRPoPMXgFyACAPOcnAYFLK7fSrkDAR6rQmnAe/KBfmBNhQCDbkGtP0yyO8gsU+FHLYgL4EClGgvgDR9zudcCrT9PchVX4q49YmKc5AmkLNBsQDyOygsQK4iygCQoo8FHLGg0AcFIDQm3gPpvXg1zlu88j++2ACFPB51CAmgbf9xYcIGEAAEDSAWM1ATAAC4CbdSzzGZLwAAAABJRU5ErkJggg==
I download a web browser open source from GitHub. In this project, the Programmer does this and this is worked:
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// Get link-URL.
String url = (String) msg.getData().get("url");
Log.i("get url" , url);
}
};
So I write this code in my app, But handleMessage not be run. Do I need to do anything else to use handleMessage method?
Do you know another way to get a URL in google search results?
Finally, after days, I found a solution. Please try this way:
#Override
public void onCreateContextMenu(#NonNull ContextMenu menu, #NonNull View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
String url = null, imageUrl = null;
WebView.HitTestResult result = ((WebView) v).getHitTestResult();
switch (result.getType()) {
case WebView.HitTestResult.SRC_ANCHOR_TYPE:
url = result.getExtra();
break;
case WebView.HitTestResult.IMAGE_TYPE:
imageUrl = result.getExtra();
break;
case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
case WebView.HitTestResult.EMAIL_TYPE:
case WebView.HitTestResult.UNKNOWN_TYPE:
Handler handler = new Handler();
Message message = handler.obtainMessage();
((WebView) v).requestFocusNodeHref(message);
url = message.getData().getString("url");
if ("".equals(url)) {
url = null;
}
imageUrl = message.getData().getString("src");
if ("".equals(imageUrl)) {
imageUrl = null;
}
break;
}
showLongPressMenu(url, imageUrl);
}

How to disable Copy but enable Paste in a WebView?

I am using a WebView to show my website on my mobile Android app. I have disabled text selection in the WebView as I want to disable Copy.
I actually wish to allow the user to Paste a text but not Copy.
How can I do that please ?
public class MainActivity extends AppCompatActivity {
WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
webview = findViewById(R.id.webView);
webview.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String host = Uri.parse(url).getHost();
String domain = "www.google.fr";
if (host.equals(domain)) {
// This is my website, so do not override; let my WebView load the page
return false;
} else {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
}
});
webview.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return true;
}
});
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webview.loadUrl("https://www.google.fr");
}
#Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
}
}
}
As you know to copy a text you need to long press it to select.
So please add a longClickListener to the webview which will show anything else on long click instead of copying the text.
mWebView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return true;
}
});
mWebView.setLongClickable(false);
But this will also disable using PASTE so to paste content from clipboard. I will suggest add a small button beside it and add an onClickListener to it which will paste the copied content to wherever you want.
ClipboardManager mClipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
String pasteData = "";
if (!(mClipboard.hasPrimaryClip())) {
} else if (!(mClipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN))) {
} else {
ClipData.Item item = mClipboard.getPrimaryClip().getItemAt(0);
copiedText = item.getText().toString();
}

Why is my fullscreen for youtube crashing?

I´m new to android and i´m using the first time webview, fragment, drawer...
I have the problem that with my code after pressing fullscreen in the video my app is crashing.
And i have no idea what is going wrong...
WebViewFragmentVideos
public class WebViewFragmentVideos extends Fragment {
WebView webView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Retrieving the currently selected item number
int position = getArguments().getInt("position");
String url = getArguments().getString("url");
// List of rivers
String[] menus = getResources().getStringArray(R.array.Websitesenglish);
// Creating view corresponding to the fragment
View v = inflater.inflate(R.layout.fragment_layout, container, false);
// Updating the action bar title
getActivity().getActionBar().setTitle(menus[position]);
//Initializing and loading url in webview
webView = (WebView)v.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl(url);
webView.setWebChromeClient(new MyChromeClient());
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
});
return v;}
class MyChromeClient extends WebChromeClient {
String url = getArguments().getString("url");
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
Intent intent = new Intent(null, LandVideoAct.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("video", url);
startActivity(intent);
}
}
}
and
LandVideoAct
public class LandVideoAct extends Activity {
WebView webView, fullweb;
String url = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setTheme(android.R.style.Theme_Light_NoTitleBar_Fullscreen);
setContentView(R.layout.landfull);
url = getIntent().getStringExtra("video") + "?fs=1";
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
webView = (WebView) findViewById(R.id.fullwebview);
if (Build.VERSION.SDK_INT < 8) {
webView.getSettings().setPluginsEnabled(true);
} else {
webView.getSettings().setPluginState(PluginState.ON);
}
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
LandVideoAct.this.finish();
}
});
webView.loadUrl(url);
}}
I hope you dudes can help me with my problem.
Thank you!!
this piece of line of code is not allowed in android.
Intent intent = new Intent(null, LandVideoAct.class);
coming to your crash problem. Its mainly because of a above line of code. When full screen of video in webview is called , its gives call to android system ie onShowCustomView(View view, CustomViewCallback callback). Where you above line of code is failing.
instead of that use activity context or application context
Intent intent = new Intent(context, LandVideoAct.class);

Android WebView error for high density screens

I have an Android application which uses a WebView to render web page. In css I have set to show everything twice as big for high density screens (like Nexus 7 2013). If I open the web page from the browser, Everything shows as it should. But when I run the app, everything is very small.
Is there any way to determine why the application WebView shows content for lower density screens but browser (Chrome) shows as it should!
Device: Nexus 7 2013
// I used this class and my code is working fime at my side please try this may be it will help you
public class WebViewActivity extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
private TextView header_maintext;
private TextView headeroptiontext;
private RelativeLayout back;
private String url_string="http://www.google.com";
private String header_maintext_string="Your text";
/** Called when the activity is first created. */
#SuppressLint("SetJavaScriptEnabled") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.webview_layout);
webview = (WebView)findViewById(R.id.webview01);
header_maintext= (TextView)findViewById(R.id.header_maintext);
header_maintext.setText(header_maintext_string);
headeroptiontext = (TextView)findViewById(R.id.headeroptiontext);
headeroptiontext.setVisibility(View.GONE);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
back = (RelativeLayout) findViewById(R.id.back_layout);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(webview.canGoBack() == true)
{
webview.goBack();
}
else
{
finish();
}
}
});
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(WebViewActivity.this, "My application", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(WebViewActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl(url_string);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack() == true){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
I think this article should help explain what you need to do: https://developers.google.com/chrome/mobile/docs/webview/pixelperfect
I suspect that the difference between Chrome and WebView boils down to the WebSettings that are being applied to the WebView.

How I get URL from webview on click

How can I get "clicked URL" from webview on its click event??
#Override
public void onClick(View v) {
if( v.getId() == R.id.webview) {
//Here i want to get clicked url
}
}
Thanks in advance.
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url){
webView.loadUrl(url);
// Here the String url hold 'Clicked URL'
return false;
}
});

Categories

Resources