I am a beginner in android platform and making an app with help of webview and javascript.when I run my code on real device it displays nothing.any help would be appreciable.
Here is my code:
public class MainActivity extends AppCompatActivity {
WebView view_1,view_2;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
String url_1="<script type=\"text/javascript” src=\"http://ds.claymcenter.com/embed.js\">\n" +
"requestAd('Rh8uGpcrlYMjXN1s', 'banner', 'ads', '320' , ‘50');\n" +
"</script>\n" +
" \n" +
"<div id='ads'></div>";
String url_2="https://paytm.com/";
view_1 = (WebView) findViewById(R.id.webViewGoogle);
view_2 = (WebView) findViewById(R.id.webViewFacebook);
view_1.getSettings().setJavaScriptEnabled(true);
view_1.loadData(url_1, "text/html", null);
view_2.getSettings().setJavaScriptEnabled(true);
view_2.loadUrl(url_2);
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view_1.reload();
view_2.reload();
}
});
} }
I always have a hell of a time trying to get things like this to work, and I don't remember exactly how I did some of this stuff, but here are some ideas:
First thing to try: Wrap that string in url_1 in <html><body>...</body></html> tags.
Second thing to try: You might have to use some kind of "onDocumentReady" event to call your javascript when the js file is completely loaded.
Third thing thing to try: Split out the function call like so:
String url_1="<script type=\"text/javascript\” src=\"http://ds.claymcenter.com/embed.js\">\n" +
"</script>\n" +
"<div id='ads'></div>";
String call = "javascript:requestAd('Rh8uGpcrlYMjXN1s', 'banner', 'ads', '320' , ‘50');\n"
Load the html with the js file then use WebViewClient.onPageFinished() to see when to load the javascript call (don't cut & paste this code, this is just a template):
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
// TODO: need to find out what is in url when html with js file loads
if (urlMatches()) {
view.loadData(call, "application/javascript", null); // not sure about the mime type
}
}
});
This is like "onDocumentReady" but doing it in the Java code.
You might be getting stuck because of this statement from the loadData docs:
Note that JavaScript's same origin policy means that script running in a page loaded using this method will be unable to access content loaded using any scheme other than 'data', including 'http(s)'. To avoid this restriction, use loadDataWithBaseURL() with an appropriate base URL.
So the last thing to try would be using loadDataWithBaseURL.
Related
I am unable to get some javascript to run successfully in the onPageFinished() method of my WebViewClient.
I am porting over an iOS app and they are doing the same thing, waiting for page to load, then using Javascript to hide some of the HTML items.
I don't use Javascript much but am not sure why it keeps failing to work correctly. Right now what happens is the page loads, then onPageFinished is called, and the page reloads and the text 'none' shows up in the top left corner.
I've attached my WebViewClient and then all the WebView setup I am doing in onCreate too. I have also included some commented out code of what I have tried before and that code also did not work.
// Manages the behavior when URLs are loaded
private class Browser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url, headers);
return true;
}
#JavascriptInterface
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//view.loadUrl("javascript:document.getElementById('navbar_bg').style.display = 'none';");
//webView.loadUrl("javascript:document.getElementById(\"content\")");
view.loadUrl("javascript:document.getElementById(\"navbar_bg\").style.display=\"none\";");
}
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mobile_homework);
ButterKnife.bind(this);
homeworkId = getIntent().getIntExtra(HOMEWORK_ID_EXTRA, 0);
// Configure related browser settings
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
// Enable responsive layout
webView.getSettings().setUseWideViewPort(true);
// Zoom out if the content width is greater than the width of the viewport
webView.getSettings().setLoadWithOverviewMode(true);
//allow manual zoom and get rid of pinch to zoom
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
// Configure the client to use when opening URLs
webView.setWebViewClient(new Browser());
}
Edit: The final fix was to set variables to each change because it returns a variable when you change any item.
Final working code looked like:
view.loadUrl("javascript:var header = document.getElementById('header_bg_first').style.display='none'; " +
"var navbar = document.getElementById('navbar_bg').style.display='none'; " +
"var footer = document.getElementById('footer').style.display='none'; " +
"var iframePadding = document.getElementById('flcn_assignment').style.paddingRight='10px';");
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://").
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) {
}
}
So, reading around i read that i could "inject" javascript into a loaded webpage to programatically fill a website's form, so i tried the following:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView WebView;
WebView = (WebView) findViewById(R.id.webview);
WebView.setWebViewClient(new HelloWebViewClient());
WebView.getSettings().setJavaScriptEnabled(true);
WebView.getSettings().setBlockNetworkImage(false);
WebView.loadUrl("http://www.kingsage.es");
String username = "XXX";
String Password = "YYY";
WebView.loadUrl("javascript:document.getElementById('login_player').value='"+username+"';javascript:document.getElementById('login_passwd').value = '"+Password+"';");
}
However, when i run this on the emulator i get an error as if the website could not be found. if i turn off the second loadUrl method i load the website, but i need to fill the login form programatically!, i figure i am doing something wrong but i haven't found and answer reading around. Any help would be appreciated!!
you need to wait until the webpage is loaded (use WebViewClient) then execute your javascript
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished (WebView webView, String url)
{
webView.loadUrl("javascript:document.getElementById('login_player').value='"+username+"';javascript:document.getElementById('login_passwd').value = '"+Password+"';");
}
});
make also sure that you execute only once, not on every onPageFinished Event
I like JeanLuc's suggestion and it worked for me 98% of the way. I still needed to automatically log the user into the web page once their username and password had been entered so I did the following and its worked well, except for trying to remove the "do you want to remember the password' message.
#Override
public void onPageFinished (WebView webView, String url)
{
webView.loadUrl("javascript:document.getElementById('Login1_UserName').value='"+userName+"';javascript:document.getElementById('Login1_Password').value = '"+password+"';");
webView.loadUrl("javascript:document.getElementById('Login1_LoginButton').click();");
}
The second line selected the 'login' button and logged them in automatically. Hope it helps someone else.
Here is how I acheived it in my scenario where I had to browse a page, fill text boxes and submit.
WebView webView = FindViewById<WebView>(Resource.Id.webEspView);
webView.SetWebViewClient(new Client());
webView.Settings.JavaScriptEnabled = true;
webView.LoadUrl("http://192.168.4.1")
Then added the Client class and overloaded onPageFinished() method.
public class Client : WebViewClient
{
public override void OnPageFinished(WebView view, string url)
{
base.OnPageFinished(view, url);
string ssid = Variables.GetInitialUsername();
ssid = ssid.Trim(new char[] {'\"'});
string pass = Variables.GetInitialPassword();
var script = $"document.getElementById(\"clientId\").value = \"{ssid}\";" +
$"document.getElementById(\"branchId\").value = \"{pass}\";" +
"document.querySelector('button[type=\"submit\"]').click()";
view.LoadUrl($"javascript: {script}");
}
}
Hope it helps.
In my application I am using WebView and in that I am using JavaScript alert( ) method but its not working, no pop-up appears.
in my manifest file I have added
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
and in activity file I have added
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("file:///android_asset/demo.html");
In layout xml file I have added
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
Any clue how to enable full JavaScript in WebView?
Update
Thanks mark
the alert() method in the html file are working now :) .
Now there are two issues in WebView :
1: I am using a <textarea> in the html file that i am loading in WebView , and trying to write in Hindi language font in it, but when i try to write Hindi text it displays as symbols ( rectangle symbols like [] ) .
when i do the same in firefox browser on desktop it works fine.
any clue how to give support for multiple language in textarea in WebView ?
2: When I am clicking submit and trying to open the value of text in alert() method in another java script it doesn't work , does it mean even after using WebChromeClient
its applicable only for current loaded html page and not javascripts called from that page ?
As others indicated, setting the WebChromeClient is needed to get alert() to work. It's sufficient to just set the default WebChromeClient():
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient());
Thanks for all the comments below. Including John Smith's who indicated that you needed to enable JavaScript.
Check this link , and last comment , You have to use WebChromeClient for your purpose.
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
return super.onJsAlert(view, url, message, result);
}
});
The following code will work:
private WebView mWebView;
final Activity activity = this;
// private Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 1000);
}
});
mWebView.loadUrl("file:///android_asset/raw/NewFile1.html");
}
You can try with this, it worked for me
WebView wb_previewSurvey=new WebView(this);
wb_previewSurvey.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//Required functionality here
return super.onJsAlert(view, url, message, result);
}
});
if you wish to hide URL from the user, Show an AlertDialog as below.
myWebView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d(TAG, "onJsAlert url: " + url + "; message: " + message);
AlertDialog.Builder builder = new AlertDialog.Builder(
mContext);
builder.setMessage(message)
.setNeutralButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
}).show();
result.cancel();
return true;
}
}