evaluate Javascript doesn't run in web view - javascript

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

Related

WebView loads URL 10 times slower than phone's Chrome browser

I've been trying to figure this one out for quite a while, and yet haven't found a solution.
Inside my app I'm extracting a website's HTML through an invisible WebView component. I do not need to view the website, just get the html it loads. The website uses JavaScript to load all of its content, and therefore I need a full web renderer in order to execute that JavaScript. In its current form, I'm overriding the WebViewClient's onPageFinished method to inject JavaScript that dumps the html into a JavaScriptInterface which then processes it.
My main issue here is that when I load this URL inside my app it would take about 8 seconds, whereas loading the exact same URL in the phone's chrome browser it takes less than a second. Any suggestions as to what might be the problem?
If it could be of any help, the JavaScript that gets executed stores a cookie inside the WebView, and then tries to retrieve it, and only if it finds said cookie (which has a short expiration time) it would load the site's HTML. In this case it actually loads data formatted with JSON (about 370k characters).
Relevant WebView code:
private void initWebView(View view) {
class JSInterface{
#JavascriptInterface
public void processHTML(String scheduleJSONResponse){
if(scheduleJSONResponse.length() > 10000){
Log.d(LOG_TAG, "Finished loading JSON");
}
}
}
webView = (WebView) view.findViewById(R.id.fragment_movies_web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JSInterface(), "Android");
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d(LOG_TAG, "Page finished loading");
webView.loadUrl("javascript:window.Android.processHTML(document.getElementsByTagName('html')[0].textContent);");
}
});
webView.loadUrl(url);
}
As for why I check that the length is more than 10k characters: Sometimes onPageFinished would get called more than once, with the first call being before the JavaScript is executed, and so I get HTML containing the script to be executed which isn't what I need.
Thanks in advance for any help!
A logcat to demonstrate the issue:
08-18 22:32:23.623 26238-26238/com.michaelsvit.kolnoa I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#1e4dc08f time:502735009
08-18 22:32:23.638 26238-26238/com.michaelsvit.kolnoa W/cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 26238
08-18 22:32:31.336 26238-26238/com.michaelsvit.kolnoa D/MovieGridFragment: Page finished loading
Current code after simplifying it:
private void initWebView(View view) {
class JSInterface{
#JavascriptInterface
public void processHTML(String scheduleJSONResponse){
if(scheduleJSONResponse.length() > 10000){
Log.d(LOG_TAG, "Finished loading JSON");
}
}
}
webView = (WebView) view.findViewById(R.id.fragment_movies_web_view);
webView.getSettings().setJavaScriptEnabled(true);
//webView.addJavascriptInterface(new JSInterface(), "Android");
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d(LOG_TAG, "Page finished loading");
//webView.loadUrl("javascript:window.Android.processHTML(document.getElementsByTagName('html')[0].textContent);");
}
});
}
through an invisible WebView component..
What when it is visible?
Try it!

load a php page which has a flash by webview and crash without error log

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?

Can not call javascript function from activity

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

Using Javascript in webview

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.

How to call the JavaScript Interface methods from android web browser?

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

Categories