I'm trying to get the content of web page in android.. I've already tried using JSoup but it doesn't support using ajax..
So I'm trying to load url inside an invisible web view and get the html in onPageFinished method..
I can get the html but the ajax loaded html doesn't appear. Here's the code:
final WebView webView = (WebView) findViewById(R.id.testWebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
Log.d(TAG, "finished loading : ");
webView.loadUrl("javascript:window.HtmlViewer.showHTML" +
"('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
}
});
webView.loadUrl(url);
class MyJavaScriptInterface {
private Context ctx;
MyJavaScriptInterface(Context ctx) {
this.ctx = ctx;
}
#JavascriptInterface
public void showHTML(String html) {
Log.d(TAG, "HTML: " + html);
new AlertDialog.Builder(ctx).setTitle("HTML").setMessage(html)
.setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
}
}
So my questions are:
-Why isn't the ajax html loaded with the page html ?
-Is there another way of loading page html with ajax using a library or something like that?
You need to use webView.loadData() method to load HTML file so, Replace the Ajax loading by this way.
webView.loadData("javascript:window.HtmlViewer.showHTML" +
"('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');", "text/html; charset=utf-8",null);
I hope it will solve your problem .
Related
I want to change some values on a HTML Page, using Javascript in a Webview.
I tried many different ways to evaluate Javscript after page finished loading.
Here is my code:
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setBlockNetworkImage(false);
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:(function() { document.getElementById('options').value = '" + found.getId() + "'; ;})()");
button.performClick();
}
});
I think it means, that the method is called to early, before page is fully loaded.
Do you have any ideas?
in order to change value / content / styling in HTML using javascript also known as DOM Manipulate, then we have waiting after DOM ready or fully loaded. In this case, we load the page into widget WebView and then do our business.
I have a sample code that I always use in the same case,
...
final String url = "http://example.com";
final WebView webview = findViewById(R.id.my_webview);
final String myNewValue = "it works!";
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
// Your custom javascript here
String myCustomJS = "document.getElementById('options').innerHTML = '" +
myNewValue + "'";
// here we execute the javascript code
webview.loadUrl("javascript:(function(){" + myCustomJS + "})()");
}
});
// and here we load the url
webview.loadUrl(url);
...
I hope the code above can help you to continue working..
Update for Waiting DOM Ready
If you have use jQuery before, then you must know
// example 1: jQuery way
$(document).ready(function() {
// place our logic here
});
// example 2: native javascript way
document.addEventListener('DOMContentLoaded', function() {
// place our logic here
});
Im use this trick to manipulate page in WebView after DOM ready (in example 2 native JS way).
Another question why not using runnable?
because we never know internet speed users, let say if we set runnable to wait 3000ms or 3sec but the web not responding after runnable execution. What happened next? users will have white blank screen and keep waiting.
hope this more clear now.
reference link: https://developer.mozilla.org/.../DOMContentLoaded_event
I'm building an app which load a webpage in a webview.
In that webpage, i need to programmatically click on some links using Jquery.
Now, i know how to execute a Javascript code on the webview programmatically (see below):
WebSettings myBrowserSettings = myBrowser.getSettings();
myBrowserSettings.setJavaScriptEnabled(true);
Log.d("Stefano", "JS enabled");
myBrowser.loadUrl("javascript:document.getElementsByid('myWord').click();");
But now, I need to know how implement a Jquery function in my webview; i'm looking for the correct way to manage something like:
myBrowser.loadUrl("jquery:function($("#myAnchor").click(function(event){})");
And which is the correct way to implement the following function?
$("#a_link")[0].click();
If jquery loaded in this page, you can just call this:
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:(function() { " +
"$("#myAnchor").click(function(event){}" +
"})()");
}
});
What's your problem? It's about escaping characters?
myBrowser.loadUrl("jquery:function($(\"#myAnchor\").click(function(event){})");
I have a WebView containing HTML data. The data is generated at runtime. A main feature of my app is highlighting certain parts of this HTML data. I tried this by using javascript.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_reader_page, container, false);
webview = (WebView) rootView.findViewById(R.id.resultText);
webview.getSettings().setJavaScriptEnabled(true);
String page = makeHTML();
webview.loadUrl("file:///android_asset/jquery-1.8.2.js");
webview.loadUrl("file:///android_asset/src_javascript.js");
webview.loadData(page, "text/html", "UTF-8");
return rootView;
}
private String makeHTML() {
StringBuilder sb = new StringBuilder();
sb.append("<!DOCTYPE html>\n");
sb.append("<html>\n");
sb.append("<head>\n");
sb.append("</head>\n");
sb.append("<body>\n");
sb.append(tokenizedText + "\n");
sb.append("</body>\n");
sb.append("</html>\n");
return sb.toString();
}
tokenizedText is my at runtime generated data with this format:
<YT_SEN id="_YT_SEN_0">This is my first sentence.</YT_SEN>
<YT_SEN id="_YT_SEN_1">This is my second sentence.</YT_SEN>
...
When my data is loaded in the WebView, the user can highlight a particular sentence by giving its number. This method then calls the corresponding javascript function:
public void highlightSentence(int sent_id) {
if (android.os.Build.VERSION.SDK_INT < 19) {
webview.loadUrl("javascript:highlightSentence('_YT_SEN_" +sent_id+ "', " +color+ ")");
} else {
webview.evaluateJavascript("javascript:highlightSentence('_YT_SEN_" +sent_id+ "', " +color+ ")", null);
}
}
The javascript function for highlighting (defined inside file:///android_asset/src_javascript.js):
function highlightSentence(object,color)
{
document.getElementById(object).style.backgroundColor = color;
}
The output of Logcat when I execute the highlightSentence method:
I/chromium﹕ [INFO:CONSOLE(1)] "Uncaught ReferenceError: highlightSentence is not defined", source: (1)
Somehow the WebView can't find the highlightSentence function. I think it's because of the way I load the Javascript and JQuery files. Yet I don't know (and can't find) the proper way to load external js-files within at runtime generated HTML data.
Note: I use the WebView solely for offline use, I have no need for any internet communication whatsoever. WebView seemed like the easiest way to enable dynamic highlighting.
It seems the Javascript same origin policy is the root of the problem. The WebView will only load javascript files which are from the same origin as the html. Since no origin for the html was given, the data scheme is used as default. If, however, the data is loaded with the same base url as the javascript files, no problem arises.
Load the html data (with file:///android_asset/javascript/ being the directory of the javascript files):
webview.loadDataWithBaseURL("file:///android_asset/javascript/", page, "text/html", "UTF-8", null);
Then reference the javascript files like this inside the html:
<script src='jquery-1.8.2.js' type='text/javascript'></script>
<script src='src_javascript.js' type='text/javascript'></script>
Assuming your javascript is in the assets directory point to it with a file url
file://android_asset/<some java script file in assets>
file://android_asset/ points to the assets directory in your apk.
So you can reference the script in your html when you build it for the webview.
<script charset='utf-8' type='text/javascript'
src='file://android_asset/myjavascript.js'></script>
I want to show part of page: web form which will be filled by user.
That web form is inside this tag:
In Java, I am trying to get form by class its name(because there is only one tag with class name "form"). Then I am trying to change content with "form" content(maybe I am doing this wrong). Then trying to show content(only form) in webview.
final WebView webview = (WebView) view.findViewById(R.id.wvCheckInn);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
String javascript = "javascript: var form = document.getElementsByClassName('form');"
+ "var body = document.getElementsByTagName('body');"
+ "body.innerHTML = form.innerHTML;";
view.loadUrl(javascript);
}
});
webview.loadUrl("http://businessinfo.uz/service/inn");
Result: webview is showing whole page, which is not good for me. How to show part of page in Webview using Javascript?
In your javascript, document.getElementsByClassName() and document.getElementsByTagName() both return arrays of DOM elements (notice the 's's before "By".) This is different from getElementById(), which returns an element directly, which makes sense since IDs are unique across a valid HTML document, but tags and classes are not.
Access the first element from each array and the javascript works:
body[0].innerHTML = form[0].innerHTML;
I have a JS file that has functions to search a document for substrings.
I want to access functions inside this file by passing parameters to it (the search keyword).
I know we can use .loadUrl("javascript:~~~~~) but I'm not clear on how to do it using multiple functions.
Anyone who can point me in the right direction?
Thanks!
You can try this.
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url){
webview.loadUrl("javascript:(function() { " +
"var script=document.createElement('script');" +
"script.type='text/javascript';script.src=" + jsFileURL + ";" +
"script.onload=function("+queryString+"){//it can be your search function};"
"document.getElementsByTagName('head').item(0).appendChild(script);"+
"})()");
}
});
webview.loadUrl("http://SOMEURL");