I am currently writing a webview, it first loads a twitter page (say,
NHL, http://twitter.com/nhl)
as you can see, you can find the tweet for NHL, and each NHL tweet has
another link for user to click, e.g. bit.ly/ujcNZo
in my webview, if i click that link (i.e. bit.ly/ujcNZo), my webview,
after 1 second, doesn't display anything but a twitter icon on a white
color background, it should load the content but it didn't.
after some time of investigation, i think it has to do with the fact
that the link in the tweet (i.e. bit.ly/ujcNZo) actually opens the
link in a separate window (pop up?) and not the current page where the
link is posted, i verified this by going to NHL's twitter page on a
browser in my laptop.
My Question is,
1. is there a way i can load the content of the external link (bit.ly/
ujcNZo, for instance) in my current webview?
You can control this through the WebViewClient class. Simply extend it and override the default implementation to get the desired configuration then set it as the client for your current webview.
Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the webViewClient to a new instance of your custom WebViewClient
webview.setWebViewClient(new WebActivityClient( this ));
}
Custom Client
/** WebViewClient class for WebView in WebActivity */
private class WebActivityClient extends WebViewClient {
public static final String TAG = "WebActivityClient";
private Context context;
/** Constructor used to grab the context */
public WebActivityClient( Context context ) {
this.context = context;
}
/** Override to load every link within the page inside this webview instead of using
* android's default application
* #7 http://developer.android.com/resources/tutorials/views/hello-webview.html */
#Override
public boolean shouldOverrideUrlLoading( WebView view, String url ) {
view.loadUrl(url);
return true;
}
}
Hope this helps!
Related
let's say that i have google page loaded in webview, then i searched for something,
So the page changed, and there's a text in this page that i want to get it in my android app, in textView by using the code below
webview.loadUrl("javascript:api.getSessionID(document.querySelector(bla bla bla)");
class JSInterface {
#JavascriptInterface
public void getSessionID(String id) {
Toast.makeText(context,id, Toast.LENGTH_LONG).show();
}
How can i inject this js in the shown page in webview, not in the page that loaded first in webview which is google search page
Google just an example, i'm trying to save a session id in sharedPreferences when a user loggin in the account, which is the second page
Note: i have all the necessary codes in my full code in order to inject js and get string from it
Note2: if i reloaded the page, i will sign out
Appreciate any help !
your WebView first of all, we must tell the WebView to enable the JavaScript execution:
webview.getSettings().setJavaScriptEnabled(true);
Then we must set the WebViewClient in order to receive the onPageFinished event.
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPag`enter code here`eFinished(view, url);
webView.loadUrl(
"javascript:(function() { " +
"var element = document.getElementById('hplogo');"
+ "element.parentNode.removeChild(element);" +
"})()");
}
});
To acheive this you can evaluate javascript as,
webview.evaluateJavascript("Your JS here which will return session id",
html1 -> Log.i("HTML", html1));//session id will be printed
Also, make sure you have enabled java script to run in webview webView.getSettings().setJavaScriptEnabled(true);
EDIT
Second approach,
If you want to implement an interface which will give callback do change in your webpage as,
if (typeof YourListener != 'undefined')//check if yourlistner is undefined
yourListener.onTextChange('theReturnValue');
});
In above code the interface is called from webpage same as we do in android. Just apply JS at 'theReturnValue' here you need to retun required value from webpage.
And then add to webview that interface as,
webview.addJavascriptInterface(new WebAppInterface(getActivity(), webview), "YourListener");
also, add interface as,
public class WebAppInterface {
Context mContext;
WebView mView;
/**
* Instantiate the interface and set the context
*/
WebAppInterface(Context c, WebView w) {
mContext = c;
mView = w;
}
/**
* Show a toast from the web page
*/
#JavascriptInterface
public void onTextChange(String html) {
//you will get the callback text here
}
}
I am creating an android app for a client using a WebView.
There are some links on the client's website that play media. In order to conserve battery, I am trying to call the "FLAG_KEEP_SCREEN_ON" when a user clicks on this media link within the website. My webview uses a new MywebViewClient() in order to handle the loading of webpages inside the webview. MywebViewClient is actually a private class that overrides shouldOverrideUrlLoading(). Since this method detects when the user clicks on the link that plays media files, I tried to apply "FLAG_KEEP_SCREEN_ON". If it is not one of the pages that plays media files , I clear "FLAG_KEEP_SCREEN_ON".
The problem I am having is that since this method is inside a private class, I can't seem to get a reference for my Activity. Perhaps the call: getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); doesn't know which window to apply this flag to. I am sure its probably something minor, but I just cant seem to get the Activity that hosts the windows from inside this inner class. Here is my code so far:
Webview w;
//inside onCreate
{
w.setWebViewClient(new WebViewClient());
}
private class MyWebViewClient{
if (Uri.parse(url).getHost().equals("WebsitesHost")) {
if(w.getUrl().equals("LinkThatPlaysMediaSound" &&
!getWindow.hasFeature(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)){
getWindow.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
if(!w.getUrl().equals("LinkThatPlaysMediaSound")
getWindow.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
Add a constructor to the MyWebViewClient which takes Activity instance.
private MyWebViewClient(Activity activity)
{
this.activity = activity;
}
Pass the activity instance while creating the MyWebViewClient
new MyWebViewClient(this);
If your inner class is not static(but you consider using static), you could simple use, YourActivityName.this for activity instance.
I am using webview in my application to show canvas. On my webview there is click here button. I want to open new activity on click of this 'click here' button on webview. I dont know how to handle this click event.Need help as soon as possible.
Following is my webview class code:
public class TableWebView extends Activity {
private SharedPreferences sharedPreferences;
private String customer_id,hotel_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table_web_view);
WebView wvtable= (WebView)findViewById(R.id.webViewTable);
wvtable.setWebViewClient(new MyViewClient());
WebSettings webSettings = wvtable.getSettings();
webSettings.setJavaScriptEnabled(true);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
customer_id = sharedPreferences.getString("cust_id", "0");//if no customerid found automatically 0 will be used
hotel_id=sharedPreferences.getString("hotel_master_id","0");
wvtable.loadUrl("http://192.168.100.169/zoilo_admin/public/index.php/show-hotel-view?hotel_id="+hotel_id+"&customer_id="+customer_id+"&date_time="+ Util.selected_date_time);
}
And here is how it looks after opening that url in webview:
Binding JavaScript code to Android code
When developing a web application that's designed specifically for the WebView in your Android application, you can create interfaces between your JavaScript code and client-side Android code. For example, your JavaScript code can call a method in your Android code to start activity.
To bind a new interface between your JavaScript and Android code, call addJavascriptInterface(), passing it a class instance to bind to your JavaScript and an interface name that your JavaScript can call to access the class.
Caution: If you've set your targetSdkVersion to 17 or higher, you must add the #JavascriptInterface annotation to any method that you want available to your JavaScript (the method must also be public). If you do not provide the annotation, the method is not accessible by your web page when running on Android 4.2 or higher.
public class TableWebView extends Activity {
private SharedPreferences sharedPreferences;
private String customer_id,hotel_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table_web_view);
WebView wvtable= (WebView)findViewById(R.id.webViewTable);
wvtable.setWebViewClient(new MyViewClient());
wvtable.addJavascriptInterface(new WebAppInterface(this), "Android");
WebSettings webSettings = wvtable.getSettings();
webSettings.setJavaScriptEnabled(true);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
customer_id = sharedPreferences.getString("cust_id", "0");//if no customerid found automatically 0 will be used
hotel_id=sharedPreferences.getString("hotel_master_id","0");
wvtable.loadUrl("http://192.168.100.169/zoilo_admin/public/index.php/show-hotel-view?hotel_id="+hotel_id+"&customer_id="+customer_id+"&date_time="+ Util.selected_date_time);
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public void startNewActivity() {
//startActivity(new Intent(this, youactivityname.class));
}
}
This creates an interface called Android for JavaScript running in the WebView. At this point, your web application has access to the WebAppInterface class. For example, here's some HTML and JavaScript that call your "startNewActivity" method of your class using the new interface when the user clicks a button:
<input type="button" value="Click Here" onClick="showActivity()" />
<script type="text/javascript">
function showActivity() {
Android.startNewActivity();
}
</script>
I have a native android app in which there are two activities, 1st activity contains a button and on action of button I want to start the 2nd activity. Content of seconds activity will be from a website. Is it possible to make the 2nd activity behave like webapp ?
If I use WebView in this case, it is displaying the website inside the activity but when I try to interact with the website, it ask to open it in the browser which I don't want. I want to interact with the website within the activity.
Any help will be highly appreciated.
Thanks a ton.
Use below code... for open link in WebView itself instead of browser...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
WebView engine = (WebView) findViewById(R.id.web_view);
engine.loadUrl("https://play.google.com/store?hl=en");
engine.setWebViewClient( new HelloWebViewClient() );
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading( WebView view, String url ) {
return false;
}
}
see this link for more details... WebView should not open links in browser
I think if you set the baseURL property when creating the Webview, you'll get what you want.
Create you're own Webview where you can override the default behaviour:
private class CustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
I'm trying to launch an Activity when clicking a link inside a WebView component.
My Webview is loaded inside Main.java and I would like to launch SubActivity.java when clicking a link inside the Website which is in Main.java?
Also, how can I pass parameters to this activity?
Example: inspection://Project/1
"Inspection" is the name of my application, inspection is the Activity I would like to launch and 1 is the ID I would like to have.
You could use WebView's addJavaScriptInterface to allow JavaScript to control your application (in this case, to allow JavaScript to fire an Intent when a link is clicked).
To do this you need to pass a class instance to bind to JavaScript, this could be something like the following:
private final class JsInterface {
public void launchIntent(final String payload) {
Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// use the payload if you want, attach as an extra, switch destination, etc.
Activity.this.startActivity(new Intent(Activity.this, SomeOtherActivity.class));
}
});
}
}
Then you add that to the WebView with something along these lines:
webView.addJavascriptInterface(js, "Android");
Then in JavaScript from the WebView you just use your new "Android" object's "launchIntent" method.
One option is to override the URL loading of the web view and pick up the click you want to launch the new activity. Check out the use of a subclassed WebViewClient in the docs:
http://developer.android.com/resources/tutorials/views/hello-webview.html
Another option is to bind your activity to a custom URL scheme. It's pretty common in doing client side OAuth, frequently through the browser instead of a WebView, but it should work similarly enough. There's a full example here:
https://github.com/brione/Brion-Learns-OAuth
Which shows how to bind the url scheme handler as well as handling getting launched via the Intent it generates (see onResume() in OAUTH.java).
First Add javascript method on your webpage's button onclick()
The function defined below..
function showAndroidToast(toast) {
AndroidFunction.showToast(toast);
}
Android Code is here for javascript Interface..
public class MyJavaScriptInterface {
Context mContext;
private Activity activity;
public MyJavaScriptInterface(Activity activiy) {
this.activity = activiy;
}
#JavascriptInterface
public void showToast(String toast){
Intent i=new Intent(getApplicationContext(), Subactivity.class);
i.putExtra("data", "tosecondActivity");
startActivity(i);
}