Call JavaScript function from Android not working - javascript

I have a Webview in which a user defined website is loaded, then on the press of a button below the WebView a Javascript (from a remote url) is loaded into the page the user is on.
Then a function within this JavaScript should be fired, however it does not seem to be working.
my activity:
public class SearchViewer extends SherlockActivity {
TextView grabit;
WebView webView;
ImageView right, left;
ProgressBar progressBar;
#SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchviewer);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_arrowleft);
Intent intent = getIntent();
String url = intent.getStringExtra("URL");
String name = intent.getStringExtra("Name");
setTitle(name);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
webView = (WebView) findViewById(R.id.webView1);
webView.loadUrl(url);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
});
grabit = (TextView) findViewById(R.id.grabit);
grabit.setOnClickListener(OnClick_grabit);
right = (ImageView) findViewById(R.id.right);
left = (ImageView) findViewById(R.id.left);
right.setOnClickListener(OnClick_right);
left.setOnClickListener(OnClick_left);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
default:
return super.onOptionsItemSelected(item);
}
return false;
}
public void onStart() {
super.onStart();
EasyTracker.getInstance(this).activityStart(this);
}
public void onStop() {
super.onStop();
EasyTracker.getInstance(this).activityStop(this);
}
private OnClickListener OnClick_grabit = new OnClickListener() {
public void onClick(View v) {
webView.loadUrl("javascript: function loadScript(scriptURL) { var scriptElem = document.createElement('SCRIPT'); scriptElem.setAttribute('language', 'JavaScript'); scriptElem.setAttribute('src', scriptURL); document.body.appendChild(scriptElem);} loadScript('http://www.pathtofile.com/javascript.js');");
webView.loadUrl("javascript: initialize("+1+")");
}
};
private OnClickListener OnClick_right = new OnClickListener() {
public void onClick(View v) {
webView.goForward();
}
};
private OnClickListener OnClick_left = new OnClickListener() {
public void onClick(View v) {
webView.goBack();
}
};
When I load the javascript with just
webView.loadUrl("javascript: function loadScript(scriptURL) { var scriptElem = document.createElement('SCRIPT'); scriptElem.setAttribute('language', 'JavaScript'); scriptElem.setAttribute('src', scriptURL); document.body.appendChild(scriptElem);} loadScript('http://www.pathtofile.com/javascript.js');");
and start the Javascript initialize() function within the Javascript file it works fine.
However when I try and do the above two lines
webView.loadUrl("javascript: function loadScript(scriptURL) { var scriptElem = document.createElement('SCRIPT'); scriptElem.setAttribute('language', 'JavaScript'); scriptElem.setAttribute('src', scriptURL); document.body.appendChild(scriptElem);} loadScript('http://www.pathtofile.com/javascript.js');");
webView.loadUrl("javascript: initialize("+1+")");
It does not work, how can I go about loading the Javascript and then firing the function from android so I can pass it a value.
I have tried
private OnClickListener OnClick_grabit = new OnClickListener() {
public void onClick(View v) {
webView.loadUrl("javascript: function loadScript(scriptURL) { var scriptElem = document.createElement('SCRIPT'); scriptElem.setAttribute('language', 'JavaScript'); scriptElem.setAttribute('src', scriptURL); document.body.appendChild(scriptElem);} loadScript('http://www.pmdev.co.uk/dadg-giftgrabber/android/gift-grabber.js');");
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.loadUrl("javascript: initialize("+1+")");
}
});
}
};
but this does not work

Did you try this:
webView.loadUrl("javascript: function loadScript(scriptURL) { var scriptElem = document.createElement('SCRIPT'); scriptElem.setAttribute('language', 'JavaScript'); scriptElem.setAttribute('src', scriptURL); document.body.appendChild(scriptElem);} loadScript('http://www.pathtofile.com/javascript.js');initialize("+1+")");

Lajos' answer should work, but, if you want your last snippet to work, you'd need to call setWebViewClient with the onPageFinished that calls initialize before you actually call the loadUrl that loads the script, and even if you do that you should be careful cause you'd be calling your javascript initialize() function twice.
The thing is, loadUrl will produce a call to onPageFinished when it's done loading (even if the url is a javascript: url.

Related

unable to load html into webview from html string

I'm trying to save a page html code into a string, then load it to a webview, I managed to get full HTML code successfully, however when I try to load it into webview, somehow it webview remove all content in
Here is how I initialized webView:
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDomStorageEnabled(true);
webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
webView.getSettings().setGeolocationEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebViewClient(new MyWebViewClient());
Webclient:
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
siteAddressBar.setText(url);
view.loadUrl(url);
Site = url;
return true;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onPageFinished(WebView view, String url) {
//view.loadUrl();
view.evaluateJavascript("(function() {return document.getElementsByTagName('html')[0].outerHTML;})();", new ValueCallback<String>() {
#Override
public void onReceiveValue(final String value) {
JsonReader reader = new JsonReader(new StringReader(value));
reader.setLenient(true);
try {
if (reader.peek() == JsonToken.STRING) {
String domStr = reader.nextString();
if (domStr != null) {
htmlCode = domStr;
Log.e("Stonmrigal1",domStr);
}
}
} catch (IOException e) {
// handle exception
} finally {
//IoUtil.close(reader);
}
}
});
}
}
and Then tried to load html like this:
webView.loadData(htmlCode, "text/html; charset=utf-8", "UTF-8");
I get response like this:
<html class="js backgroundsize borderimage csstransitions fontface svg details progressbar meter no-mathml cors xxsmallview wb-enable" dir="ltr" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body></body>
</html>
Solved, I used
webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);

Webview does not load javascript to get content

I want to get all text in body tag of a url but it doesn't work. I have searched many but i could not find anything. I have also added android.permission.INTERNET also.
so what is the problem?
This is my code:
public class Activity_Main extends Activity {
#SuppressLint("JavascriptInterface")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
final TextView contentView = (TextView) findViewById(R.id.contentView);
class MyJavaScriptInterface
{
private TextView contentView;
public MyJavaScriptInterface(TextView aContentView)
{
contentView = aContentView;
}
#SuppressWarnings("unused")
public void processContent(String aContent)
{
final String content = aContent;
contentView.setText(content);
}
}
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new MyJavaScriptInterface(contentView), "INTERFACE");
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
webView.loadUrl("javascript:window.INTERFACE.processContent(document.getElementsByTagName('body')[0].innerText);");
}
});
webView.loadUrl("https://stackoverflow.com");
}
}
update #JavascriptInterface for your interface function and check
class MyJavaScriptInterface
{
private TextView contentView;
public MyJavaScriptInterface(TextView aContentView)
{
contentView = aContentView;
}
#JavascriptInterface
public void processContent(String aContent)
{
final String content = aContent;
contentView.setText(content);
}
}
and there is another way to do this is this for above KITKAT
webView.evaluateJavascript("alert('pass here some ...')", new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
}
});
this is update solution for executing js in android
full code is here
final WebView webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
final TextView contentView = (TextView) findViewById(R.id.contentView);
class MyJavaScriptInterface
{
private TextView contentView;
public MyJavaScriptInterface(TextView aContentView)
{
contentView = aContentView;
}
#JavascriptInterface
public void processContent(String aContent)
{
final String content = aContent;
contentView.setText(content);
}
}
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new MyJavaScriptInterface(contentView), "INTERFACE");
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view,url);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("document.getElementsByTagName('body')[0].innerText", new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
contentView.setText(s);
}
});
}
else {
webView.loadUrl("javascript:window.INTERFACE.processContent(document.getElementsByTagName('body')[0].innerText)");
}
}
});
webView.loadUrl("https://stackoverflow.com");
To call a JavaScript function from Android you don't need to add interface prefix:
webView.loadUrl("javascript:processContent(document.getElementsByTagName('body')[0].innerText);");
Note: You must implement the called javascript function in your HTML page. So If you are calling a third party website in your webview, you have only access to the current existing functions in that page.
e.g https://stackoverflow.com has no javascript function named INTERFACE.processContent!
On the contrary when you want to call and Android method from javascript then you need that prefix:
<script>INTERFACE.myAndroidMethod()</script>
Finally if you want to proccess the HTML content of a thirdparty webpage you can not extract the content using a Webview and JavaScript function (that not exists in that page) but you need Android codes to load the webpage content without the WebView mediation.

Inject Multiple JavaScript to Multuple Page of WebView Android

Say, I set my WebView into example.com then I clicked on the page and load the example.com/about.
In the WebView I've injected Javascript to modify the HTML on the example.com, and it worked, and the problem is, how to inject another JavaScript to modify example.com/about. I mean how to inject multiple JavaScript to a multiple page of WebView?
public class MainActivity extends AppCompatActivity {
WebView mWebView;
private int getScale() {
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
Double val = new Double(width) / new Double(100);
val = val * 100d;
return val.intValue();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
mWebView.setWebViewClient(new WebViewClient());
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
// Inject CSS when page is done loading
injectCSS();
mWebView.loadUrl("javascript:var greeting = function (name) {\n" +
" console.log(\"Great to see you,\" + \" \" + name);\n" +
"};");
super.onPageFinished(view, url);
//Inject JS to edit html
injectScriptFile(view, "script.js"); // see below ...
// test if the script was loaded
view.loadUrl("javascript:setTimeout(test(), 500)");
}
private void injectScriptFile(WebView view, String scriptFile) {
InputStream input;
try {
input = getAssets().open(scriptFile);
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close();
// String-ify the script byte-array using BASE64 encoding !!!
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
view.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var script = document.createElement('script');" +
"script.type = 'text/javascript';" +
// Tell the browser to BASE64-decode the string into your script !!!
"script.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(script)" +
"})()");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
mWebView.loadUrl("example.com");
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
}
private void injectCSS() {
try {
InputStream inputStream = getAssets().open("style.css");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
mWebView.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var style = document.createElement('style');" +
"style.type = 'text/css';" +
// Tell the browser to BASE64-decode the string into your script !!!
"style.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(style)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu); // Add menu items, second value is the id, use this in the onCreateOptionsMenu
menu.add(0, 1, 0, "Back");
menu.add(0, 2, 0, "Refresh");
menu.add(0, 3, 0, "Forward");
getMenuInflater().inflate(R.menu.menu_main, menu);
return true; // End of menu configuration
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 3: //If the ID equals 3 , go forward
mWebView.canGoForward();
item.setIcon(R.drawable.forward);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) { // Enables browsing to previous pages with the hardware back button
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { // Check if the key event was the BACK key and if there's history
mWebView.goBack();
return true;
} // If it wasn't the BACK key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
}

Get href value from anchor tag in Android WebView when link is clicked

I am loading a webpage in WebView. There is a link in the webpage, which on desktop will download the file, but in the app the link should display a Toast saying the link is disabled for the app.
I am not sure how to get the value from href of the anchor tag, when the link is clicked.
<a class="btn btn-primary" download="http://xx.xxx.com/wp-content/uploads/2015/11/abc-27-15.mp3" href="http://xx.xxx.com/wp-content/uploads/2015/11/abc-27-15.mp3">
<i class="fa fa-download"></i> Download Audio</a>
Can someone share an idea or any sample code on how to do this.
EDIT:1
Here is what I am doing currently:
private static final String URL = "http://xx.xxx.com/wp-content/uploads/";
webView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
WebView.HitTestResult hr = ((WebView) v).getHitTestResult();
String extra = hr.getExtra();
if (extra != null && extra.startsWith(URL) && extra.endsWith(".mp3")) {
Log.d("WebviewActivity", "Extra: " + extra);
Log.d("WebviewActivity", "Contains URL");
return true;
}
}
return false;
}
});
The problem with this approach is:
When i click on the link, i get the url in extra. It works fine till here. But, from next time, no matter where i click on the webview, the same extra is being returned. So even if i click on an image after i click on the url, i get the same url in the extra. Not sure if i doing anything wrong. Or is this the correct approach.
Please let me know if you need any details.
EDIT:2
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// Get link-URL.
String url = (String) msg.getData().get("url");
// Do something with it.
if (url != null) {
Log.d(TAG, "URL: "+url);
}
}
};
webView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
WebView.HitTestResult hr = ((WebView) v).getHitTestResult();
if (hr.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
Message msg = mHandler.obtainMessage();
webView.requestFocusNodeHref(msg);
}
}
return false;
}
});
webView.loadUrl(mUrl);
}
Now, i get the URL that is clicked in the last action_down event. How to get the current URL?
EDIT 3 (Attempt with webviewclient:
private class MyWebViewClient extends WebViewClient {
private static final String URL = "xx.xxx.com/wp-content/uploads/";
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (!isFinishing())
mProgressDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mProgressDialog.dismiss();
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Toast.makeText(WebviewActivity.this,
"Please check your internet " + "connection and try again",
Toast.LENGTH_SHORT).show();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("xxx", "Url: " + url);
if(url.contains(URL)) {
Log.d("xxx", "Url Contains: " + URL);
return true;
}
return false;
}
}
mMyWebViewClient = new MyWebViewClient();
webView.setWebViewClient(mMyWebViewClient);
Output in logcat when the link is clicked:
03-01 15:38:19.402 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:553] focusedNodeChanged: isEditable [false]
03-01 15:38:19.428 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:253] updateKeyboardVisibility: type [0->0], flags [0], show [true],
03-01 15:38:19.428 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:326] hideKeyboard
03-01 15:38:19.429 19626-19626/com.xx.xxx D/cr_Ime: [InputMethodManagerWrapper.java:56] isActive: true
03-01 15:38:19.429 19626-19626/com.xx.xxx D/cr_Ime: [InputMethodManagerWrapper.java:65] hideSoftInputFromWindow
Because you are using a WebView and the link is not Java script this is very easy to achieve with a WebViewClient which you can use to monitor your WebView
myWebView.setWebViewClient( new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// check something unique to the urls you want to block
if (url.contains("xx.xxx.com")) {
Toast.make... //trigger the toast
return true; //with return true, the webview wont try rendering the url
}
return false; //let other links work normally
}
} );
It's possible that because your URL ends in .mp3 the file is being treated as a resource. You should also override the shouldInterceptRequest method of the WebViewClient to check this.
#Override
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
Log.d("XXX", "Url from API21 shouldInterceptRequest : " + url);
if (url.contains(URL)) {
return new WebResourceResponse("text/html", "UTF-8", "<html><body>No downloading from app</body></html>");
} else {
return null;
}
}
public WebResourceResponse shouldInterceptRequest (WebView view, String url) {
Log.d("XXX", "Url from shouldInterceptRequest : " + url);
if (url.contains(URL)) {
return new WebResourceResponse("text/html", "UTF-8", "<html><body>No downloading from app</body></html>");
} else {
return null;
}
}
Most of the work can be done at the web page side itself. You have to write java script to identify which device is accessing the page (mobile, desktop etc) if its mobile then use java script binding technique to call the native android code to show Toast message.
http://developer.android.com/guide/webapps/webview.html
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
WebAppInterface.java
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 showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
YourHTML Page (this sample got a button click)
<input type="button" value="Say hello" onClick="showAndroidToast('Hello
Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>

Javascript in wicket ModalWindow

I have next situation: I open ModalWindow and show in it several Panels by clicking on button - and I need to attach some JavaScript on viewing concrete Panel. How can I do it?
I tried to add Behavior on my Panel:
add(new AbstractBehavior() {
private static final long serialVersionUID = 1L;
#Override
public void renderHead(IHeaderResponse response) {
String js = "function myFunction(parameter) { alert('asdasd1'); }";
response.renderJavascript(js, null);
response.renderOnDomReadyJavascript("$(document).ready(function() { alert('test2'); myFunction("+paramsFromWicket+") }); ");
}
});
but it doesn't work :(
My bad, I found solution. I had to use AbstractAjaxBehavior
add(new AbstractAjaxBehavior() {
private static final long serialVersionUID = 1L;
#Override
public void onRequest() {
}
#Override
public void renderHead(IHeaderResponse response) {
String js = "function myFunction(param) { alert('Hello World'); } $(document).ready(function() { myFunction(" paramFromWicket + "); });";
response.renderOnDomReadyJavascript(js);
}
});

Categories

Resources