WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setPluginsEnabled(true);
myWebView.loadUrl("file:///android_asset/index.html");
myWebView.loadUrl("javascript:hello()");
It doesnt work in 4.0 emulator or real device. I have proper tag in html like
<script type="text/javascript">..</script>
and i can fire it from firefox's console with no problem (it doesnt call alert command, i know it doesnt work in android)
I am out of solutions, please help me.
Btw this function call seems useless here because it is for testing, i will give a parameter later if this works.
Edit:
<h1 id="title"></h1>
....
<script type="text/javascript">
function hello()
{
console.log("hello");
var title = document.getElementById("title");
title.innerHTML = "hello";
}
</script>
The problem is that there is no guarantee that the page has been loaded when you call the javascript. Make sure that you call the javascript function only when the page is completely loaded.
The following code (quoted from http://lexandera.com/2009/01/injecting-javascript-into-a-webview/) will give you a heads up.
final WebView webview = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
webview.getSettings().setJavaScriptEnabled(true);
/* WebViewClient must be set BEFORE calling loadUrl! */
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
webview.loadUrl("javascript:(function() { " +
"document.getElementsByTagName('body')[0].style.color = 'red'; " +
"})()");
}
});
webview.loadUrl("http://code.google.com/android");
Related
I'm trying to interact with my web view so I can get a value to later insert into a file (which is not important), When trying to execute the JavaScript I tried adding script tags and also removing the function which both ways don't work. I don't get any error in any way at all. How do I execute JavaScript in a loaded web view?
WebView myWebView = (WebView) findViewById(R.id.webload);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("https://www.example.co.uk");
myWebView.setWebViewClient(new WebViewClient());
myWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
view.evaluateJavascript("(function(){alert('e');})();", givenValue -> {
if (givenValue != null && !givenValue.isEmpty() && !givenValue.equals("null")) {
}
});
super.onPageFinished(view, url);
}
}
);
Hey i have worked used webview alot in my recent projects and the right way to execute the javascript in a loaded webpage is below.
webview.loadUrl("javascript:(function() {
// Your Javascript code , you can access dom elements and do whatever you want
})()");
Add this line in onPageFinished function of WebViewClient. also don't forget to enable javascript of your webview
I am unable to get some javascript to run successfully in the onPageFinished() method of my WebViewClient.
I am porting over an iOS app and they are doing the same thing, waiting for page to load, then using Javascript to hide some of the HTML items.
I don't use Javascript much but am not sure why it keeps failing to work correctly. Right now what happens is the page loads, then onPageFinished is called, and the page reloads and the text 'none' shows up in the top left corner.
I've attached my WebViewClient and then all the WebView setup I am doing in onCreate too. I have also included some commented out code of what I have tried before and that code also did not work.
// Manages the behavior when URLs are loaded
private class Browser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url, headers);
return true;
}
#JavascriptInterface
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//view.loadUrl("javascript:document.getElementById('navbar_bg').style.display = 'none';");
//webView.loadUrl("javascript:document.getElementById(\"content\")");
view.loadUrl("javascript:document.getElementById(\"navbar_bg\").style.display=\"none\";");
}
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mobile_homework);
ButterKnife.bind(this);
homeworkId = getIntent().getIntExtra(HOMEWORK_ID_EXTRA, 0);
// Configure related browser settings
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
// Enable responsive layout
webView.getSettings().setUseWideViewPort(true);
// Zoom out if the content width is greater than the width of the viewport
webView.getSettings().setLoadWithOverviewMode(true);
//allow manual zoom and get rid of pinch to zoom
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
// Configure the client to use when opening URLs
webView.setWebViewClient(new Browser());
}
Edit: The final fix was to set variables to each change because it returns a variable when you change any item.
Final working code looked like:
view.loadUrl("javascript:var header = document.getElementById('header_bg_first').style.display='none'; " +
"var navbar = document.getElementById('navbar_bg').style.display='none'; " +
"var footer = document.getElementById('footer').style.display='none'; " +
"var iframePadding = document.getElementById('flcn_assignment').style.paddingRight='10px';");
I have occurred a problem. In my app,I load a url(a php page) by webview. It runs fun in many devices.But in a TV device,it offen exit without any error log.Now I know it is because the php page load a swf flash.But the page show well in the browser in the Tv.My code is as follows:
mWebView = (WebView) v.findViewById(R.id.shopWebView);
mWebView.setOnKeyListener(this);
mWebView.setInitialScale(100);
WebSettings webSet = mWebView.getSettings();
webSet.setJavaScriptEnabled(true);
webSet.setBlockNetworkImage(true);
webSet.setSupportZoom(true);
webSet.setBuiltInZoomControls(true);
webSet.setSupportMultipleWindows(true);
webSet.setUseWideViewPort(true);
webSet.setLoadWithOverviewMode(true);
// webSet.setPluginState(PluginState.ON);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
view.getSettings().setBlockNetworkImage(false);
}
});
mWebView.loadUrl(URL_SHOP);
Who can tell me what's wrong with my code or the reason of this case?(Forgive my poor English.)
Use WebChromeClient. That May help.
webView.setWebViewClient(new MyWebClient());
public class MyWebClient extends WebChromeClient {
}
I have solved this problem.I did like this:Before webview load url,I set the webview gone;and set webview visible in onPageFinished().Although I have solved the problem,but I don't know the exactly reason of that condition.If anyone know,please tell me.Is it because the TV's vedio memory or other things like that?
So, reading around i read that i could "inject" javascript into a loaded webpage to programatically fill a website's form, so i tried the following:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView WebView;
WebView = (WebView) findViewById(R.id.webview);
WebView.setWebViewClient(new HelloWebViewClient());
WebView.getSettings().setJavaScriptEnabled(true);
WebView.getSettings().setBlockNetworkImage(false);
WebView.loadUrl("http://www.kingsage.es");
String username = "XXX";
String Password = "YYY";
WebView.loadUrl("javascript:document.getElementById('login_player').value='"+username+"';javascript:document.getElementById('login_passwd').value = '"+Password+"';");
}
However, when i run this on the emulator i get an error as if the website could not be found. if i turn off the second loadUrl method i load the website, but i need to fill the login form programatically!, i figure i am doing something wrong but i haven't found and answer reading around. Any help would be appreciated!!
you need to wait until the webpage is loaded (use WebViewClient) then execute your javascript
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished (WebView webView, String url)
{
webView.loadUrl("javascript:document.getElementById('login_player').value='"+username+"';javascript:document.getElementById('login_passwd').value = '"+Password+"';");
}
});
make also sure that you execute only once, not on every onPageFinished Event
I like JeanLuc's suggestion and it worked for me 98% of the way. I still needed to automatically log the user into the web page once their username and password had been entered so I did the following and its worked well, except for trying to remove the "do you want to remember the password' message.
#Override
public void onPageFinished (WebView webView, String url)
{
webView.loadUrl("javascript:document.getElementById('Login1_UserName').value='"+userName+"';javascript:document.getElementById('Login1_Password').value = '"+password+"';");
webView.loadUrl("javascript:document.getElementById('Login1_LoginButton').click();");
}
The second line selected the 'login' button and logged them in automatically. Hope it helps someone else.
Here is how I acheived it in my scenario where I had to browse a page, fill text boxes and submit.
WebView webView = FindViewById<WebView>(Resource.Id.webEspView);
webView.SetWebViewClient(new Client());
webView.Settings.JavaScriptEnabled = true;
webView.LoadUrl("http://192.168.4.1")
Then added the Client class and overloaded onPageFinished() method.
public class Client : WebViewClient
{
public override void OnPageFinished(WebView view, string url)
{
base.OnPageFinished(view, url);
string ssid = Variables.GetInitialUsername();
ssid = ssid.Trim(new char[] {'\"'});
string pass = Variables.GetInitialPassword();
var script = $"document.getElementById(\"clientId\").value = \"{ssid}\";" +
$"document.getElementById(\"branchId\").value = \"{pass}\";" +
"document.querySelector('button[type=\"submit\"]').click()";
view.LoadUrl($"javascript: {script}");
}
}
Hope it helps.
I tried to display a web page using the android WebView but the javascript animations are very slow ... I tried to open the same page from the browser and it works correctly ...
The problem is that i'm using using a JavaScript Interface to call some Java methods (With the WebView) :
mWebView = (WebView) findViewById(R.id.spacetree);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new MyWebChromeClient());
mWebView.addJavascriptInterface(new JavaScriptInterface(this), "API");
mWebView.loadUrl("MyURL");
And i don't know how to use this interface when i launch this page on a browser (so the animations can be displayed correctly) using this code :
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("MyUrl"));
startActivity(i);
PS: The WebPage is stored locally ('file:///android_asset')
its very easy:
mWebView.loadUrl("javascript: example()");
this can you do after a page is loaded and wont redirect you to a diffrent URL, if your JS is correct.
hope this helps
in file HTML create function
function androidResponse(index) {
AndroidFunction.sendToAndroid(index);
}
in file java code
final IJavascriptHandler handle = new IJavascriptHandler(
ListMapActivity.this);
webMap.addJavascriptInterface(handle, "AndroidFunction");
define class IJavascriptHander
final class IJavascriptHandler {
ListMapActivity ctx;
IJavascriptHandler(ListMapActivity c) {
ctx = c;
}
#JavascriptInterface
public void sendToAndroid(String text) {
final String msgeToast = text;
// this is called from JS with passed value
myHandler.post(new Runnable() {
#Override
public void run() {
// This gets executed on the UI thread so it can safely
// modify Views
shopMapPager.setCurrentItem(Integer.parseInt(msgeToast));
}
});
Toast t = Toast.makeText(getApplicationContext(), text, 2000);
t.show();
}
}
and callBack result with
webMap.loadUrl("javascript:androidResponse();void(0)");