I am trying to display a page containing HTML with javascript in android webview with the below code.But this doesn't seem to work.Can anyone help me out.
public class MainActivity extends ActionBarActivity {
WebView browser;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
browser = (WebView) findViewById(R.id.webView);
browser.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
browser.setWebViewClient(new Callback());
browser.getSettings().setJavaScriptEnabled(true);
loadTime();
}
void loadTime() {
String page = "<html>"
+"<head>"
+"<title>chat window</title>"
+"<script type=\"text/javascript\">"
+ "var bccbId = Math.random(); document.write(unescape('%3Cdiv id=' + bccbId + '%3E%3C/div%3E'));"
+" window._bcvma = window._bcvma || [];"
+" _bcvma.push([\"setAccountID\", \"423771628801258096\"]);"
+" _bcvma.push([\"setParameter\", \"WindowParameters\", \"vr=&vi=&ve=" + gblQnbVars["gUserEmail"] + "&vp=" + gblQnbVars["gMobileNum"] + "&vn= "+ gblQnbVars["gCustomerFirstName"]+ "&lc=\"]);"
+"var bcLoad = function(){"
+ " if(window.bcLoaded) return; window.bcLoaded = true;"
+" var vms = document.createElement(\"script\");"
+"vms.type = \"text/javascript\";"
+" vms.async = true;"
+" vms.src = ('https:'==document.location.protocol?'https://':'http://') + \"vmss.boldchat.com/aid/423771628801258096/bc.vms4/vms.js\";"
+"var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(vms, s);"
+"};"
+"if(window.pageViewer && pageViewer.load) pageViewer.load();"
+" else if(document.readyState==\"complete\") bcLoad();"
+" else if(window.addEventListener) window.addEventListener('load', bcLoad, false);"
+" else window.attachEvent('onload', bcLoad);"
+ "function FireBoldChat() {"
+" try {"
+ " _bcvmw.chatWindow({"
+ "type: \"chat\","
+ "rdid: \"\","
+ "cwdid:\"1504531236710990857\","
+ "ve:\"<%=visitor email%>\","
+ "vp:\"<%=visitor phone%>\","
+ "vn:\"<%=visitor name%>\","
+ "embed: true"
+ "});"
+" } catch (e) {"
+"setTimeout(FireBoldChat, 500)"
+" }"
+" };"
+" </script>"
+"</head>"
+"<body onload=\"FireBoldChat();\">"
+"</body>"
+"</html>";
System.out.println(page);
browser.loadDataWithBaseURL("x-data://base", page,
"text/html", "UTF-8",
null);
}
private class Callback extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
loadTime();
return(true);
}
}
Whenever I load my this webpage in default browser its working perfectly. Where i have did wrong.
The documentation for loadData() says
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.
Now you do use loadDataWithBaseURL(), but your base URL is x-data://base yet you try to load a script from http(s)://vmss.boldchat.com. I think that can cause your problem.
I got same problem. I just replace
vms.src="https://" +\"vmss.boldchat.com/aid/423771628801258096/bc.vms4/vms.js\";"
this will be come if not add necessary java script file
before run please check your XML format is ok
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
for more :http://developer.android.com/guide/webapps/webview.html
and you may not call layout
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
WebView webView = (WebView)
browser = findViewById(R.id.webview);
browser.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
browser.setWebViewClient(new Callback());
browser.getSettings().setJavaScriptEnabled(true);
}
}
try this some time this will be help
thank
Looking at your code, didn't see the run time changes in html file.
So create html file using above page variable & put in assets folder.
once this done write following code:
public class ViewWeb extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView vistaWeb = (WebView) findViewById(R.id.webView1);
vistaWeb.setWebChromeClient(new Callback());
vistaWeb.setWebViewClient(new Callback());
vistaWeb.clearCache(true);
vistaWeb.clearHistory();
vistaWeb.getSettings().setJavaScriptEnabled(true);
vistaWeb.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
vistaWeb.loadUrl("file:///android_asset/aboutcertified.html"); // now it will not fail here
}
}
Hope this will help you.
I suspect the variable gblQnbVars I did not find any reference to it in your snippet. Can you confirm if it is accessible in your code? May be that's throwing error.
Related
I am using a WebView to display a website into my application.
When I'm loading my WebView, I first need to fill the authentification form and then redirect to the original URL.
My WebView keep reloading again and again.
Could anyone explain to me how to use a WebView with "automatic" filling please?
final WebView mWebView;
//Show webview into the app via a popup
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(context);
mAlertDialog.setTitle(R.string.menuBuyCredit);
mWebView = new WebView(context);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(ConstantsClass.URL_BUY_CREDIT);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//In order to automatically fill the form
final String mJavaScript = "javascript:" +
"document.getElementById('Login').value = '" + ClientSingleton.getInstance().getmLogin() + "';" +
"document.getElementById('Password').value = '" + ClientSingleton.getInstance().getmPassword() + "';" +
"document.getElementById('Btn_Envoyer').click()";
view.loadUrl(mJavaScript);
view.loadUrl(ConstantsClass.URL_BUY_CREDIT);
view.pageDown(true);
}
});
mAlertDialog.setView(mWebView);
mAlertDialog.setNegativeButton(R.string.closeDrawer, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
mAlertDialog.show();
} ```
You should use something like
Put this in global
boolean loadedAlready = false;
inside onPageFinished method
if (view.getUrl().equals(ConstantsClass. URL_BUY_CREDIT) && !loadedAlready) {
loadedAlready= true;
view.load(ConstantsClass.URL_BUY_CREDIT);
}
How do I run a JavaScript code into webview?
Is it possible to use an existing URL and put the JavaScript into that URL from webview (not onPageFinished) but I am unsure on how to do that, so I am trying to make a short html that will run the JavaScript.
webView.addJavascriptInterface(this, "Android");
String page = "<html>" +
"<body>" +
"<script>" +
"document.write(javascript:Android.getdate())" +
"</script>" +
"</body>" +
"</html>");
webView.loadUrl(page)
I expect that when loadUrl is run with that html string it will run the getdate() function and display the result.
You need to enable JavaScript for the WebView in it's WebSettings first.
WebSettings webSettings = webView.getSettings();
if (webSettings != null) {
webSettings.setJavaScriptEnabled(true);
}
Also if you want to load HTML instead of a URL, you need to use loadData()instead of loadUrl().
public class MainActivity extends AppCompatActivity {
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
if (webSettings != null) {
webSettings.setJavaScriptEnabled(true);
}
//Enable setWebContentsDebuggingEnabled to use Chrome DevTools in debug build
if (BuildConfig.DEBUG) {
WebView.setWebContentsDebuggingEnabled(true);
}
webView.addJavascriptInterface(this, "Android");
String page = "<html>" +
"<body>" +
"<h1>Test</h1>" +
"<script type=\"text/javascript\">" +
" document.write(Android.getDate());" +
"</script>" +
"</body>" +
"</html>";
webView.loadData(page, "text/html", "utf-8");
}
#JavascriptInterface
public String getDate() {
return "<p>The current date is " + new Date().toString() + "</p>";
}
}
I created a webview on android studio and want to place the android post request response inside textarea on webiview . The post request is working correctly and i receive data from server but my Javascript function inside webview never get called to populate the textarea. Could an expert look at my code and show me how to fix it.Thanks in advance.
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView= (WebView) findViewById(R.id.activity_main_webview);
mWebView.loadUrl("file:///android_asset/index.html");
mWebView.getSettings().setJavaScriptEnabled(true);
// Force links to open in the WebViewinstead of in a browser
mWebView.setWebViewClient(new WebViewClient());
}
#Override
protected void onResume()
{
super.onResume();
new PostClass().execute();
}
private class PostClass extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
final TextView outputView = (TextView) findViewById(R.id.postOutput);
try {
StrictMode.setThreadPolicy(new Builder().permitAll().build());
HttpURLConnection myURLConnection = (HttpURLConnection) new URL("http://myownapi.com/api").openConnection();
myURLConnection.setReadTimeout(60000);
myURLConnection.setConnectTimeout(60000);
myURLConnection.setRequestMethod("POST");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setRequestProperty("API_KEY", "12345_ABC_MNO_12345678_123ABC");
myURLConnection.setRequestProperty("Connection", "Keep-Alive");
myURLConnection.addRequestProperty("Content-length", "");
OutputStream os = myURLConnection.getOutputStream();
os.close();
myURLConnection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
StringBuffer sb = new StringBuffer();
System.out.println(sb);
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
outputView.setText(sb.toString());
//outputView.setText("finished");
mWebView.loadUrl("javascript:MyFunction(" + sb.toString() + ")");
//mWebView.loadUrl("javascript:MyFunction()");
} catch (Exception e) {
}
return null;
}
}
}
html code inside webview:
<html>
<head>
<script>
function MyFunction(myVar)
{
//var myVar = 'test data';
var myTextArea = document.getElementById('myArea');
myTextArea.innerHTML += myVar;
};
</script>
</head>
<body>
<br>
<br>
<textarea id="myArea" rows="30" cols="40"></textarea>
</body>
Hello there you are missing quotes in
mWebView.loadUrl("javascript:MyFunction(" + sb.toString() + ")");
Right now you what you call is this
MyFunction(string)
instead this should be
MyFunction('string')
So instead of passing a string you are trying to pass the variable like an object.
mWebView.loadUrl("javascript:MyFunction('" + sb.toString() + "')");
In my Android Application, I have a WebView, before it displays anything from it though, I made it so that certain elements on my site do not display with javascript.It however only works on the first load, if you actually navigate through the site(click on a post for example) it will display all of the elements I don't want it to. It was working perfectly fine before, and now I cannot figure out why it isn't working. I'd appreciate any help!
mWebView = (WebView) view.findViewById(R.id.webView);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
return false;
}
#Override
public void onPageStarted(final WebView view, final String url, final Bitmap favicon) {
bar.setVisibility(View.VISIBLE);
mWebView.setVisibility(View.INVISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{
mWebView.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('fa fa-youtube')[0].style.display='none'; " +
"document.getElementsByClassName('fa fa-twitter')[0].style.display='none'; " +
"document.getElementsByClassName('menu-primary-container')[0].style.display='none'; " +
"document.getElementsByClassName('menu-toggle')[0].style.display='none'; " +
"document.getElementsByClassName('widget_slider_area')[0].style.display='none'; " +
"})()");
bar.setVisibility(View.GONE);
mWebView.setVisibility(View.VISIBLE);
super.onPageFinished(view, url);
}
});
mWebView.loadUrl("http://mywebsite.com");
I am trying to load data into android webview using
webview.loadDataWithBaseURL("", htmlcontent, "text/html", null, "");
a method returns htmlContent from a StringBuilder which populates html data.
I have enabled javascript and set webChromeClient as follows
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient());
webview.addJavascriptInterface(new JSClass(), "Android");
my interface to javascript:
class JSClass {
public void getHTMLContent(String html)
{
Log.i(Global.TAG, "HTMLContentReceived: "+html);
}
}
and my javascript in html page:
<script type="text/javascript">
var ele = document.getElementsByClassName('test');
for(var i=0;i<ele.length;i++){
ele[i].onclick = function(){
window.Android.getHTMLContent(this.innerHTML);
}
}
</script>
but somehow the javascript is not returning any value.
It works fine with loadData(url) where url is a simple webpage in assets folder
Please help
Thanks in advance
You don't have any baseURL to use, since you're loading a dynamical generated HTML.
For this reason webview.loadData(htmlcontent, "text/html", null); should be more than enough.
Javascripts don't throw any exceptions in Java code. Remember that JS is not that type-safe/strict as Java code ... My way of doing is to put logs between sensitive Javascript calls to see if that line passes and to check values. Since you didn't provide the HTML, I would setup the WebChomeClient and override the onConsoleMessage:
webview.setWebChromeClient(new MyChromeClient());
private class MyChromeClient extends WebChromeClient {
#Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
String message = consoleMessage.message() + " -- line " + consoleMessage.lineNumber();
switch (consoleMessage.messageLevel()) {
case ERROR:
logErrorMessage(message);
break;
default:
logInfoMessage(message);
break;
}
return true;
}
private void logInfoMessage(String message) {
Log.i("JSTag", message);
}
private void logErrorMessage(String message) {
Log.e("JSTag", message);
}
}
From your JavaScript you would then call for example: console.log('check my value:' + (ele != null)). More info on this here.
Looking at your JavaScript code, I can't understand to what points this.innerHTML.