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

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

Related

evaluate Javascript doesn't run in web view

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

Java, JavaFx : Inserting a HTML&JS(static,no internet) project inside a JavaFX container

I am working on a task in which we need to put one of our HTML & JS based project inside a JavaFX project or any other suitable containers which are out there. The purpose is to create an app, which can directly be deployed and would prevent any users from checking out the source code of HTML & JS.
Some time back when I was checking out JavaFX, I read that it supports JS, and JS can be used with it. Is there any way to create a container inside which I can put my HTML&JS files by giving path, etc?
How can I go about this? Whatever I am trying to do, what is it called. Any help, pointers, suggestions, would be nice.
Initial test
public class Main extends Application {
private Scene scene;
MyBrowser myBrowser;
#Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("Test web");
myBrowser = new MyBrowser();
scene = new Scene(myBrowser, 1920, 1200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
class MyBrowser extends Region {
final String hellohtml = "hello.html";
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
public MyBrowser(){
URL urlHello = getClass().getResource("hello.html");
webEngine.load(urlHello.toExternalForm());
getChildren().add(webView);
}
}
As #sillyfly suggested use a WebView:
File f = new File(..);
// ..
final WebView webview = new WebView();
webview.getEngine().load(f.toURI().toURL().toString());
The hard part for me is always to figure out the right location to be used to reference the file.
Another option is when you have the HTML in the form of a string to load that as content:
String html = ...
webview.getEngine().loadcontent(html)
Be sure to check out at least the JavaDoc on WebView and WebEngine`

Unable to execute Js code in WebView in Cordova Project

I have two activity, one main activity(A) is an CordovaActivity, then I use intent to start another activity(B), in B i have an WebView(not CordovaActivity), and after I use this webview to load a simple webpage (alert something), I found the js code is not executed at all, even if I enable javascript by calling setttings.setJsenabel(true);
I start activity B from A
Load Url from webview in Activity B
simple web page
in the device, it does not alert anything
However, if I change the webview to CordovaWebView instead of the original Android native one, it works.....
That's because plain WebView doesn't support showing alerts by itself. You need to provide a WebChromeClient to it that implements WebChromeClient.onJsAlert method. For example:
mywebView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(
WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(view.getContext())
.setTitle("Alert")
.setMessage(message)
.setPositiveButton("Ok",
new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
});

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.

Categories