How do I run javascript inside of an html string using webview? - javascript

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>";
}
}

Related

Android WebVIew, click problems

I was wondering how to make a webview use the javascript in an app.
I have on click events happening everywhere on this page but it won't work on the webview.
It works on desktop no problem but this webview is giving me issues.
This is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.setClickable(true);
webView.setEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("{my website}");
webView.setOnClickListener( this);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
Log.d( TAG, "Action down X:" + event.getX()+ " Y:" + event.getY());
break;
case MotionEvent.ACTION_UP:
Log.d( TAG, "Action up X:" + event.getX()+ " Y:" + event.getY());
break;
case MotionEvent.ACTION_MOVE:
Log.d( TAG, "Action move X:" + event.getX()+ " Y:" + event.getY());
break;
case MotionEvent.ACTION_CANCEL:
Log.d( TAG, "Action cancel X:" + event.getX()+ " Y:" + event.getY());
break;
}
return true;
}
You have to override method shouldOverrideUrlLoading() when setting WebViewClient. Please check from here.

WebView with Javascript keep reloading

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);
}

Android webView - javascript code is not getting called

I try to load this javascript in my webview:
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
website = "https://www.blizz-z.de";
myWebView = findViewById(R.id.blizzView);
WebSettings settings = blizzView.getSettings();
settings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
#Override
// Notify the host application that a page has finished loading.
public void onPageFinished(WebView view, String url)
{
myWebView.loadUrl(
"javascript:(function() {" +
"setInterval(function() {" +
+ "jQuery('#myInput').css('background', '#'+(Math.random()*0xFFFFFF<<0).toString(16));"
+ "}, 1000);"
+ "});"
);
}
}
...
}
But it is not getting executed. If I execute the script in my desktop browser, then it works. It changes the background color of my search bar on my website just for test purposes.
Is setInterval not supported in webView?
Update:
I tried it with the function js from #mohkamfer's answer:
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
website = "https://www.blizz-z.de";
blizzView = findViewById(R.id.blizzView);
WebSettings settings = blizzView.getSettings();
settings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
#Override
// Notify the host application that a page has finished loading.
public void onPageFinished(WebView view, String url)
{
js(myWebView, "(function() {" +
"setInterval(function() {" +
+ "jQuery('#myInput').css('background', '#'+(Math.random()*0xFFFFFF<<0).toString(16));"
+ "}, 1000);"
+ "});"
);
}
}
...
}
public void js(WebView view, String code)
{
String javascriptCode = "javascript:" + code;
if (Build.VERSION.SDK_INT >= 19) {
view.evaluateJavascript(javascriptCode, new ValueCallback<String>() {
#Override
public void onReceiveValue(String response) {
Log.i("debug_log", response);
}
});
} else {
view.loadUrl(javascriptCode);
}
}
But it makes no difference.
Are you deploying on API 19 or higher? If so you'll have to use WebView#evalulateJavascript instead of WebView#loadUrl
I always use this method to simplify and quicken things a bit
public void js(String code) {
if (Build.VERSION.SDK_INT >= 19) {
this.evaluateJavascript(code, new ValueCallback<String>() {
#Override
public void onReceiveValue(String response) {
}
});
} else {
this.loadUrl("javascript:" + code);
}
}
I figured it out... I just had to call the code with jQuery(document).ready(function() {. The code was executed but did not changed anything because it was executed before the DOM was ready...
Solution:
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
website = "https://www.blizz-z.de";
myWebView = findViewById(R.id.blizzView);
WebSettings settings = blizzView.getSettings();
settings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
#Override
// Notify the host application that a page has finished loading.
public void onPageFinished(WebView view, String url)
{
js(myWebView, "jQuery(document).ready(function() {" +
"setInterval(function() {" +
+ "jQuery('#myInput').css('background', '#'+(Math.random()*0xFFFFFF<<0).toString(16));"
+ "}, 1000);"
+ "});"
);
}
}
...
}
public void js(WebView view, String code)
{
String javascriptCode = "javascript:" + code;
if (Build.VERSION.SDK_INT >= 19) {
view.evaluateJavascript(javascriptCode, new ValueCallback<String>() {
#Override
public void onReceiveValue(String response) {
Log.i("debug_log", response);
}
});
} else {
view.loadUrl(javascriptCode);
}
}
Credits to #mohkamfer for contributing the js function.

Android Javascript function only works on initial load

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");

The HTML with javascript is not getting loaded in android webview

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.

Categories