Webview does not load javascript to get content - javascript

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.

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

Android WebView Auto Sign In

Following is the code which is I am implementing:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
webView = (WebView) findViewById(R.id.webTask);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setSaveFormData(false);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
else webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.loadUrl("javascript:document.getElementById('user_id').value='" + new String ("xxx")+ "';javascript:document.getElementById('password').value = '" + new String("xxx") + "';");
}
});
webView.loadUrl(URL);
But nothing happens infact web view turns blank and shows text written on its left corner "xxx"
Please help. already searched 3 to 4 hours and of no avail
At last i have solved the problem. the javascript was not being run because my targeted sdk was >= KITKAT.
So, in order to avoid the problem you have to use webView.evaluateJavascript(yourScript,null); for devices running on API level 19 or above.
Sample Code
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
webView.evaluateJavascript(yourScript,null);
}
else
{
webView.loadUrl(yourScript);
}

How to call JavaScript from webview in fragment?

Below code, I am using to load webview in fragment and I want to call JavaScript function from webview but below code is not working.
public class MainActivity extends ActionBarActivity
{
public void loadUrlInWebView(String url,String positon)
{
WebViewFragment fragment = new WebViewFragment();
Bundle data = new Bundle();
data.putString("url",url);
fragment.setArguments(data);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
}
var url ="javascript:mobileApp.openLoginMenu()";
loadUrlInWebView(url,null);
}
public class WebViewFragment extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
url = getArguments().getString("url");
View rootView = inflater.inflate(R.layout.activity_main, container, false);
webView = (WebView) rootView.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JsInterface(getActivity()),"AndroidJSObject");
webView.loadUrl(url);
webView.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
return rootView;
}
}
To call a javascript into android you can call addJavascriptInterface().
For more explanation please follow this link Building Web Apps in WebView.
And the thing to keep in mind is,
When you want to call an android method from javascript method, the method name should be called on the string name you have provided while calling addJavascriptInterface() precisely in your case something like this in your javascript
AndroidJSObject.yourmethod
Inside javascript file.
if android:targetSdkVersion >=17
add #SuppressLint("JavascriptInterface") in onCreated method
and
class InJavaScript {
#JavascriptInterface
public void runOnAndroidJavaScript(String status) {
collectionStatus.setCollectionStatus(status);
}
}
watch out #JavasscriptInterface.

My JavaScript is not changing color or dimensions as I expected

I am trying to use JavaScript in an Android webview. I used following code. I did not get color changed or offset height of body.
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new myJavaScriptInterface(webview), "jsInterface");
webview.loadUrl("file:///android_asset/sample/contents.html");
//webview.loadData("file:///android_asset/sample",convertStreamToString(inputStream), "text/html", "UTF-8");
webview.loadUrl("javascript:" +
"document.getElementsByTagName('p')[0].style.color='red';" +
"");
wbview.loadUrl("javascript:window.jsInterface.EchoText(document.body.offsetHeight);");
//webview.
}
class myJavaScriptInterface
{
WebView mywebview;
public myJavaScriptInterface(WebView webview)
{
this.mywebview=webview;
}
public void EchoText(String message)
{
Toast.makeText(mywebview.getContext(), message, Toast.LENGTH_SHORT).show();
}
}
What am I missing?
I think this is because your page is not loaded (still loading) when you are using webview.loadUrl("javascript:" + ...) statements.
Try the following...
webview.loadUrl("file:///android_asset/sample/contents.html");
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView webview, String url) {
webview.loadUrl("javascript:" +
"document.getElementsByTagName('p')[0].style.color='red';");
wbview.loadUrl("javascript:" +
"window.jsInterface.EchoText(document.body.offsetHeight);");
}
});

Android WebView

With reference to this WebView tutorial, in particular this method
private void setupWebView(){
String MAP_URL = "http://gmaps-samples.googlecode.com/svn/trunk/articles-android-webmap/simple-android-map.html";
String centerURL = "javascript:centerAt(" + mostRecentLocation.getLatitude() + ","+ mostRecentLocation.getLongitude()+ ")";
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
//Wait for the page to load then send the location information
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url){
webView.loadUrl(centerURL);
}
});
webView.loadUrl(MAP_URL);
}
I've noticed that if I place the webView.loadUrl(centerURL); directly after
webView.loadUrl(MAP_URL); like this
private void setupWebView(){
String MAP_URL = "http://gmaps-samples.googlecode.com/svn/trunk/articles-android-webmap/simple-android-map.html";
String centerURL = "javascript:centerAt(" + mostRecentLocation.getLatitude() + "," + mostRecentLocation.getLongitude()+ ")";
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
//Wait for the page to load then send the location information
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url){
//DO NOTHING
}
});
webView.loadUrl(MAP_URL);
webView.loadUrl(centerURL);
}
it no longer works. So the centreAt(..) javascript method is contained int the MAP_URL.
I'm wondering if the webView.loadUrl(..) method returns before the url has actually been loaded.
It looks that way since the top method waits for it to load fully before running the javascript
Yes, webView.loadUrl() is asynchronous: it returns immediately and WebView keeps working in it's own thread.
To monitor WebView page loading use WebViewClient.onPageFinished(..):
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do something here
}
});

Categories

Resources