how to hide my website header in android webview? I have tried javascript function in my mainactivity.java but not worked, Please hep, Thanks in advance!
This is Im tried
#Override
public void onPageFinished(WebView view, String url)
{
myWebView.loadDataWithBaseURL("javascript:(function() { " +
"document.get('header')[0].style.display='none'; " +
"})()");
}
hope you have added
mWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadDataWithBaseURL("javascript:(function() { " +
"var header = document.getElementById(\"header\"); " +
"header.parentNode.removeChild(header);" +
"})()");
}
Related
I hava webView application in Android. I have defined the javascript interface myapp and I can successfully call it from webpage. I am testing the interface in an ajax function but when I call the functions in ajax success callback, nothing happens:
My Javascript codes in webpage:
function notif(t,v){
try {
myapp.Logit("start"); // I can see this message in Logcat
}catch(err){}
$.ajax({
method:"post",
url:"test.asp",
data:{t:t,v:v},
success:function(data){
alert("done"); // Alert works in webpage
try {
myapp.Logit("finish"); // Nothing happens in Logcat
}catch(err){}
}
})
}
And this is the simple function in Android app to log events in logcat:
#JavascriptInterface
public void Logit(String message){
Log.i("message:",message);
}
How are you injecting the Java object into this WebView?
Please make sure that the you are injecting the Java object into the WebView as below. Without that you won't be able to access the Java objects's method in WebView
webView.addJavascriptInterface(new MyApp(), "MyApp");
It will also help to see if you are getting any error in the debug console. Article on how to setup the remote debugging
below is the sample working code. Hope this helps.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE))
{ WebView.setWebContentsDebuggingEnabled(true); }
}
myWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
System.out.println("Web View loaded");
}
});
Button loadBtn = (Button) findViewById(R.id.load_button);
loadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String unencodedHtml =
"<!DOCTYPE html>\n" +
"<html>\n" +
" <head>\n" +
" <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script>\n" +
" <script>\n" +
" $(document).ready(function(){\n" +
" $(\"button\").click(function(){\n" +
" $.ajax({\n" +
" method:\"get\",\n" +
" url: \"https://my-json-server.typicode.com/typicode/demo/posts\", \n" +
" success: function(result){\n" +
" alert(\"done\"); \n" +
" try {\n" +
" MyApp.Logit(\"finish\"); // Nothing happens in Logcat\n" +
" }catch(err){}\n" +
" }});\n" +
" });\n" +
" });\n" +
" </script>\n" +
" </head>\n" +
" <body>\n" +
" <button>Get External Content</button>\n" +
" </body>\n" +
"</html>";
String encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(),
Base64.NO_PADDING);
myWebView.loadData(encodedHtml, "text/html", "base64");
}
});
myWebView.addJavascriptInterface(new MyApp(), "MyApp");
}
}
class MyApp
{
#JavascriptInterface
public void Logit(String message){
Log.i("message:",message);
}
}
Background:-
I am trying to call a #JavascriptInterface annotated method processVideo() form the loadUrl() of webview to get callback when someone click on any video on the webpage.
The following is my approach and it's working perfectly
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
webView = findViewById(R.id.web_view_facebook);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.addJavascriptInterface(this, "Downloader");
webView.setWebViewClient(new WebViewClient() {
#Override
public void onLoadResource(WebView view, String url) {
webView.loadUrl("javascript:(function prepareVideo() { "
+ "var el = document.querySelectorAll('div[data-sigil]');"
+ "for(var i=0;i<el.length; i++)"
+ "{"
+ "var sigil = el[i].dataset.sigil;"
+ "if(sigil.indexOf('inlineVideo') > -1){"
+ "delete el[i].dataset.sigil;"
+ "console.log(i);"
+ "var jsonData = JSON.parse(el[i].dataset.store);"
+ "el[i].addEventListener('click',function(){Downloader.processVideo(jsonData['src'],jsonData['videoID']);});"
+ "}" + "}" + "})()");
}
});
webView.loadUrl("https://m.facebook.com");
}
#JavascriptInterface
public void processVideo(final String vidData, final String vidID) {
try {
Toast.makeText(this, "Download Started", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Download Failed: " + e.toString(), Toast.LENGTH_LONG).show();
}
}}
Now The Problem:-
But as i load custom javascript function in loadUrl(), i lost the ability to play video on click.
i think it will happen as i intercepted and load my custom code
So what i want to achieve is when any user click on video, then the video should play and also i get the callback that i wanted at first place
What i have tried so far:-
to play the video on click, i used
addEventListener('click',function(){
var video = document.getElementById(jsonData['videoID']);
video.play(); }
This one is working perfectly to play the video.
but when i use this solution with my callback like following
addEventListener('click',function(){
Downloader.processVideo(jsonData['src'],jsonData['videoID']);
var video = document.getElementById(jsonData['videoID']);
video.play(); }
then I am not able to get callback in my processVideo().
If i use them individually, both functionality (callback and play video) working perfectly inside addEventListener(), but not working together.
This code line: var video = document.getElementById('jsonData['videoID']') throws an error because you used more than two 's in one argument.
Try replacing by var video = document.getElementById(jsonData['videoID']).
Hope this helps.
I have solved this issue and i am pasting complete code here:
webView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
//query_string = "" + url;
// view.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()");
}
#Override
public void onLoadResource(WebView view, String url)
{
// query_string=""+url;
webView.loadUrl("javascript:(function prepareVideo() " +
"{ "
+ "var el = document.querySelectorAll('div[data-sigil]');"
+"var ID;"
+"var SRC;"
+ "for(var i=0;i<el.length; i++)"
+ "{"
+ "var sigil = el[i].dataset.sigil;"
+ "if(sigil.indexOf('inlineVideo') > -1)" +
"{"
+ "delete el[i].dataset.sigil;"
+ "console.log(i);"
+ "var jsonData = JSON.parse(el[i].dataset.store);"
+"ID=jsonData['videoID'];"
+"SRC=jsonData['src'];"
// +"document.getElementsByTagName(\"'+jsonData['videoID']+'\")[0].play();"
+ "el[i].setAttribute('onClick','FBDownloader.processVideo(\"'+jsonData['src']+'\",\"'+jsonData['videoID']+'\");');"
+ "}"
+ "}"
+ "})()");
}
});
JAVA ACTIVITY FUNCTION WHICH IS CALL FROM JAVASCRIPT WEBVIEW
public void processVideo(final String vidData, final String vidID)
{
this.vidData=vidData;
this.vidID=vidID;
Get_Download_Permission();
showtoast("video ID ="+this.vidID);
webView.loadUrl("https://www.facebook.com/video/embed?video_id="+this.vidID);//193766537709747/");
}
I've been trying for several hours to run some Javascript in an android webview in which there is html parsed by Jsoup. And despite all my attempts to make it work, I'm still not able to do it.
I've searched all over Google and tried all the answers I found, however none of them did the trick I tried using a method and here's what I ended up with:
Document doc = Jsoup.connect("http://example.com/").get();
Elements web_body = doc.select("body").first().children();
Elements web_head = doc.select("head").first().children();
String javascript = "document.querySelector('h1').innerText='f';"; //Replaces 'Example Domain' with 'f': just an example js code.
WebView webview = findViewById(R.id.webview_id);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
String html_content = "<html>" + "<head>" + web_head.toString() + "</head>" + "<body>" + web_body.toString() + "</body>" + "</html>";
webview.loadDataWithBaseURL("", html_content, "text/html", "UTF-8", "");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webview.evaluateJavascript(javascript, null);
} else {
webview.loadUrl("javascript:(function(){" + javascript + "})()");
}
The code above shows the example page but javascript doesn't work at all: the app doesn't show any error messages nor crashes.
I'm using a phone with Android O (8.0).
I hope the above information will be useful. I'm still a beginner in Java and any help would be greatly appreciated!
Well I replaced:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webview.evaluateJavascript(javascript, null);
} else {
webview.loadUrl("javascript:(function(){" + javascript + "})()");
}
with
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView webview, String url) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webview.evaluateJavascript(javascript, null);
} else {
webview.loadUrl("javascript:(function(){" + javascript + "})()");
}
}
});
and it just WORKS!
I am trying to remove an HTML element in webview. Here is my code. Everything compiles fine.
I have looked at other questions and none of the answers work for me.
// load web url
final WebView webView = (WebView) mRootView.findViewById(R.id.fragment_main_webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:(function() { " + "document.getElementsByTagName('publicTabs')[0].style.display=\"none\"; " + "})()");
}
});
webView.loadUrl(mUrl);
When I open the app on my phone, no webpage loads. Just blank. If I remove:
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:(function() { " + "document.getElementsByTagName('publicTabs')[0].style.display=\"none\"; " + "})()");
}
});
the webpage loads.
Also, can someone tell me how to remove multiple HTML elements at the same time?
Any help would be appreciated.
Heres the answers: Also check if the element is a class or Id in the website. Like the one below in my code.
String url = "https://www.example.com";
final WebView webView = (WebView) findViewById(R.id.fragment_main_webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.getSettings().setSavePassword(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setSaveFormData(true);
webView.getSettings().setSupportZoom(false);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setSupportMultipleWindows(false);
webView.getSettings().setLightTouchEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('header home_header')[0].style.display='none'; " +
"document.getElementsByClassName('glyphicon glyphicon-menu-hamburger')[0].style.display='none'; " +
"document.getElementsByClassName('searchBottomLinks_index searchBottomLinks_internal')[0].style.display='none'; " +
"document.getElementsByClassName('list-unstyled list-inline')[0].style.display='none'; " +
"document.getElementsByClassName('row')[0].style.display='none'; "+
"document.getElementsByClassName('header home_header')[0].style.display='none'; " +
"document.getElementsById('header-inner')[0].style.display='none'; " +
"document.getElementsById('fixed-header')[0].style.display='none'; " +
"document.getElementsByClassName('collapse navbar-collapse')[0].style.display='none'; " +
"document.getElementsByClassName('navbar navbar-inverse sidebars')[0].style.display='none'; " +
"document.getElementsByClassName('footer')[0].style.display='none'; " +
"document.getElementsByClassName('footer2')[0].style.display='none'; " +
"document.getElementsByClassName('container')[0].style.display='none'; " +
"document.getElementsByClassName('acad-slider')[0].style.display='none'; " +
"})()");
}
});
webView.loadUrl("https://www.example.com");
}
}
I had the same problem, and fixed it with adding "var x=" before the javascript line :
webView.loadUrl("javascript:var x = document.getElementsByClassName('header')[0].style.display='none';");
In my app one of my Activity is based on a webpage..I want to load a webpage that will display the ExamSeatingPlan from my Student Portal.I am logging into the website using JavaScript and then I want to load the page which will display my ExamSeatingPlan on the same webview. The problem I am facing is when I logged in using javascript the login is successful, but then it's not loading the web page that display my ExamSeatingPlan. It loads the required page if I minimize the app and then after a few second maximize it. I think I didn't implement the onPageFinished correct.It will be very helpful if someone help me solve the problem.
Thanks
MainActivity.java
package com.example.ebad.badwae;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
final String url = "http://111.68.99.8/StudentProfile/";
final String urltesting = "http://111.68.99.8/StudentProfile/ExamSeatingPlan.aspx";
WebView view;
boolean loaded;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (WebView) findViewById(R.id.webview);
WebSettings webSettings = view.getSettings();
webSettings.setJavaScriptEnabled(true);
view.loadUrl(url);
view.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView views, String urls) {
view.loadUrl("javascript: {" + "document.getElementById('ctl00_Body_ENROLLMENTTextBox_tb').value = '" + "01-134121-061" + "';" +
"document.getElementById('ctl00_Body_PasswordTextBox_tb').value = '" + "123456789" + "';" +
"document.getElementsByName('ctl00$Body$LoginButton')[0].click();" + "};");
onPageFinishede(views, urls);
}
public void onPageFinishede(WebView views, String urls) {
if (!loaded) {
views.loadUrl(urltesting);
loaded = true;
}
}
});
}
}
Now It is loading the new page but it is using almost 80% of CPU. Is there any way to reduce the CPU usage?
Try calling the loadotherpage() after your first page finished.
So you need to change the following lines
view.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView views, String urls) {
view.loadUrl("javascript: {" + "document.getElementById('ctl00_Body_ENROLLMENTTextBox_tb').value = '" + "01-134121-061" + "';" +
"document.getElementById('ctl00_Body_PasswordTextBox_tb').value = '" + "123456789" + "';" +
"document.getElementsByName('ctl00$Body$LoginButton')[0].click();" + "};");
}
});
loadotherpage();
to
view.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView views, String urls) {
view.loadUrl("javascript: {" + "document.getElementById('ctl00_Body_ENROLLMENTTextBox_tb').value = '" + "01-134121-061" + "';" +
"document.getElementById('ctl00_Body_PasswordTextBox_tb').value = '" + "123456789" + "';" +
"document.getElementsByName('ctl00$Body$LoginButton')[0].click();" + "};");
if(!loaded){
loadotherpage();
loaded = true;
}
}
});