Get all the DOM with webview - javascript

Im trying to get the html response in my webview, (yes I know that I can do the same without webview).
On my page finished I have this code:
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:window.HTMLOUT.showHTML('<html>'+document.getElementsByTagName(\"*\")+'</html>');");
The response:
<html>[object HTMLCollection]</html>
If I try this:
view.loadUrl("javascript:window.HTMLOUT.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
Then this is the response:
<html><head></head><body></body></html>
Any idea?

Related

Is there a way to have an webview on android where I can inject css before the page is loading?

I need to have a webview where I inject CSS to a webpage before it is loaded so that the injected css is applied to the loading page itself. On iOS webviews this is a native feature, but as far as I know, there is no feature like that in the android native webview.
I tried using flutters inAppWebview for that, but according to their doc at https://inappwebview.dev/docs/javascript/user-scripts/ they can't provide that feature because of the same reason and therefore the behavior isn't guaranteed.
Is there some alternative webview out there that provides this kind of feature?
You can modify or stylish web pages with your own custom CSS style sheet in Android web-view. To do that, we have just a CSS file and a few lines of code needed.
like~
#Override
public void onPageFinished(String URL, WebView view) {
super.onPageFinished(view, URL);
// Inject CSS when page is done loading
injectCSS();
});
// Load a web
webl.loadUrl("https://www.example.com");
}
// Inject CSS method: read style.css from assets folder
// Append stylesheet to document head
private void injectCSS() {
try {
InputStream inputStream = getAssets().open("black.css");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
webl.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();
};
Hope it will helpful
reference - https://www.programmersought.com/article/54381014286/
You can add your CSS code in the public void onLoadResource(WebView view, String url) method then it will be applied before the page load is finished.
It will help you to prevent users to sees the actual webpage before your CSS gets applied.
below is the full code
webView.setWebViewClient(new MyWebViewClient());
String url = getString(R.string.blogURL);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
WebViewClient class code
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
//if in the website used any javascript to interact with CSS then also add in this method, otherwise remove it from this method.
view.loadUrl("javascript:(function() { " +
"var h1 = document.getElementById('et_mobile_nav_menu').style.visibility='hidden'; " +
"})()");
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
view.loadUrl("javascript:(function() { " +
"var h1 = document.getElementById('et_mobile_nav_menu').style.visibility='hidden'; " +
"})()");
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(BlogActivity.this, "Something is wrong while loading blog. Please try again", Toast.LENGTH_SHORT).show();
}
}
hope it will help someone

add data to webview html input in android

i have a webview, am trying to load a webpage as shown in figure attached below, there is a dropdown and two inputs in need to get it loaded by filling these values given by us in android webview
I have tried this code but its not working
final String sectionName = getIntent().getStringExtra("sectionName");
final String consumerNumber = getIntent().getStringExtra("consumerNumber");
final String billNumber = getIntent().getStringExtra("billNumber");
this.web = (WebView) findViewById(R.id.web);
this.web.loadUrl(Constants.Payment_URL);
this.web.getSettings().setJavaScriptEnabled(true);
this.web.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
Log.e("TAG", "sectionName:" + sectionName);
view.loadUrl("javascript:$($(\"#sectionCode option\")[" + sectionName + "]).prop('selected','selected');$('#ConsumerNo').val('" + consumerNumber + "');$('#billNo').val('" + billNumber + "');");
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
});
I need the web view get loaded with those values given in programenter image description here
Yes you can do that with the help of javascript.
You can inject javascript into your webview in many ways.
I would advice you to use JavaSCript injector library. You can find it here.
https://github.com/henrychuangtw/WebView-Javascript-Inject

Android load pdf in Webview locally from SDcard

I am trying to load a pdf from my sd onto webview.
I know it is not possible to direct load a pdf in webview. So I have a html file which renders the file and load the pdf.
sample from http://www.worldwidewhat.net/2011/08/render-pdf-files-with-html5/
Android Code:
final WebView webView = (WebView) findViewById(R.id.magazineWebView);
final ProgressBar spinner = (ProgressBar) findViewById(R.id.magazineSpinner);
webView.setBackgroundColor(0xFFFFFFFF);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSaveFormData(true);
webView.getSettings().setBuiltInZoomControls(mgznCanZoom);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
spinner.setVisibility(View.GONE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
String webPath = "http://mysite/demo/pdf-js/index.htm"; //WORKS
String file_name2 = "pdf-js/index.htm"; //LOAD HTML BUT NOT PDF
String file_uri = MAGAZINE_FOLDER + file_name2;
String sdPath = Uri.parse("file://"
+ Environment.getExternalStorageDirectory()
+ file_uri).toString();
webView.loadUrl(sdPath); //webPath
Erros from logcat:
I/chromium: [INFO:CONSOLE(0)] "XMLHttpRequest cannot load file:///storage/emulated/0/MyApp/Magazine/pdf-js/compressed.tracemonkey-pldi-09.pdf. Cross origin requests are only supported for protocol schemes: http, data, chrome, https.", source: file:///storage/emulated/0/MyApp/Magazine/pdf-js/index.htm (0)
I/chromium: [INFO:CONSOLE(52)] "Uncaught TypeError: Cannot read property 'Symbol(Symbol.iterator)' of null", source: file:///storage/emulated/0/MyApp/Magazine/pdf-js/lib/pdf.js (52)
I/AppLifecycle: onActivitySaveInstanceState
But ->
If I store this file in the cloud and load it as above, it will work fine.
Anyone know why this wont load locally ?
Thanks guys.
P.S I know there are lot of these question online. I have looked around and not found a solution.
I am not able to use librarys like this https://github.com/JoanZapata/android-pdfview

Android Webview not loading javascript injected images

I have the following application:
From start the webview is created and will load a local (to the app) HTML file.
This local HTML file contains some javascript that is able to update the HTML when data parsed to it.
Only when i parse data to it the images will not load, however a am able to see the HTML change and see the correct img tags appear with the correct URL's. I tested the javascript and the data that i send to it in the browser and it works.
My app:
private static final String URL = "file:///android_asset/overview.html";
private WebView wView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Set settings
wView = (WebView) findViewById(R.id.webView);
wView.getSettings().setJavaScriptEnabled(true);
wView.getSettings().setUseWideViewPort(true);
wView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//TMP DEBUDDING
wView.setWebContentsDebuggingEnabled(true);
//Create interface called "AppBridge" for JavaScript
wView.addJavascriptInterface(new WebAppInterface(this), "AppBridge");
wView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:testInject('Hello World');");
view.loadUrl("javascript:updateOverview(SOME DATA);");
}
#Override
public void onLoadResource (WebView view, String url) {
Log.v(TAG, "Webview load Resouce " + url);
}
});
wView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d(TAG, message);
return true;
}
});
wView.loadUrl(URL);
Does anyone have an idea what is prohibiting the webview from loading my injected html images.
---- UPDATE ----
Some extra testing, when adding the img tag manually to the html the image is loaded and then when adding it again trough javascript it is shown. But only the same image is show all others are still not loaded.
After about 8 hours of testing , debugging and head bashing. I found the solution.
Inspired by the following article http://artemzin.com/blog/android-webview-io/
By overriding shouldInterceptRequest the WebView wil load the images.
wView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:testInject('Hello World');");
view.loadUrl("javascript:updateOverview("SOME DATA");
}
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
return super.shouldInterceptRequest(view, request);
}
});

Webview not loading javascript

I have loaded an html to the webview. I want to increase the font size of the p tag dynamically. For that I made a javascript and loaded after loading the html. But it is not working. What may be the problem??
Thanks in advance
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
String javascript="all_paras = document.getElementsByTagName('p');\n";
javascript=javascript+"for(i=0;i<all_paras.length;i++) {all_paras[i].style.fontSize = '30px';}";
mWebView.loadUrl("javascript:(" + javascript + ")()");
System.out.println("Script executed..");
}
});
Got the answer... Problem was with the syntax of javascript...
Working code is
String javascript="function() {all_paras = document.getElementsByTagName('p');\n";
javascript=javascript+"for(i=0;i<all_paras.length;i++) {all_paras[i].style.fontSize = '30px';}}";

Categories

Resources