How to call a javascript function with a browser in Java? - java

I have implemented a simple browser in java which load a html page(I wrote it), I want to call my javascript function, in my java my class!
I try the following code, but it didn't execute the script!
browser.execute("<script type='text/javascript'> "
+"loadMap("+lat+","+lng+");"
+" </script>");

Try
browser.execute("loadMap("+lat+","+lng+");");
You don't need to create a script tag to execute the script. Just execute the actual JavaScript code. Refer to this sample.

Related

How can I execute JS on server-side?

I'm on a Java EE project and I need to use the value of a JS var on my Java code but my java code is execute before my JS (logic)
But I need the value of a JS var to execute my java and I think it will work if I execute my js on server-side but I don't know how to do this ...
My code is something like this :
JS :
function(){
var url = "an url of 20.000 char that I can't pass in GET and who is automatically generated by google chart API"
}
Java :
<%
String urlChart = "value of my "url" var in js";
session.setAttribute("urlChart", urlChart);
%>
But I don't know how tu put the value of my JS var un my java code. Can you help me ?
Somebody said me that I have to use AJAX but I don't know how to use it.
That is not possible in my understanding. you must switch to some other alternate solutions. you can use CGI or PHP or AJAX.
http://www.w3schools.com/ajax/
You can check this similiar question: how to send a string to a servlet from javascript using xmlhttprequest
If this won't help, then you need to provide more details because i'm not sure if i understand your problem.

Usage of ScriptInjector in GWT

I want to use javascript library in java source code. I read sth about it and I read, that I should use ScriptInjector. This class has 2 inner classes: ScriptInjector.FromString and ScriptInjector.FromUrl. I want to load javascript library from local file, so I should use from string. How to do it?
ScriptInjector.fromString("myLibrary.js");
does not work. Where to add library?
1) fromUrl - creates script tag with specified src attribute and appends it to the page. E.g.
ScriptInjector.fromUrl("http://example.com/my-script.js").inject();
will simply produce:
<script type="text/javascript" src="http://example.com/my-script.js" />
You can host your files on the web site and inject each of them on demand
2) fromString - creates script tag with specified body of the script, so:
ScriptInjector.fromString("alert('Injected!')").inject();
will give
<script type="text/javascript">
alert('Injected!')
</script>
In this case JS code is a part of your compiled GWT code and browser doesn't require to load it with separate request. I think it is possible to include native JS file into compiled output with TextResource. So you need following:
Define resources
public interface JsResources extends ClientBundle {
final JsResources INSTANCE = GWT.create(JsResources.class);
#Source("first.js")
TextResource firstScript();
#Source("second.js")
TextResource secondScript();
}
Inject required script
ScriptInjector.fromString(JsResources.INSTANCE.firstScript().getText()).inject();
To use .fromString() you'd have to load the JS into a String and pass that.
If you need to load the script using the .fromUrl() you'll have to put it somewhere "Internet" accessible, since the inject() ends up in
private static native void nativeSetSrc(JavaScriptObject element, String url) /*-{
element.src = url;
}-*/;
(See it here)
So: Extract or otherwise expose the script to your webserver.
Cheers,

Why does Rhino Javascript engine complain a function does not exist?

Please forgive me, as I am a Java man dabbling in Javascript business :)
I wanted to be able to define a set of integration test cases to be easy to script against a Java application. I thought Javascript would be a perfect language to script against. To that end, I am using the Rhino engine that comes with JDK 7, via Java's Scripting API. The scripts would have access to Java classes already defined in the application, and could be reused to define use case scenarios for integration testing.
In the Java application, I have binded the javascript engine itself to the script as jsengine, so that I can load javascript files (Including a JavaScript file during Rhino eval).
I have two Javascript files, as defined below:
Function.js:
function send(msg) {
send.sendMessage(msg);
}
TestCase.js
jsengine.eval(new java.io.FileReader("Function.js");
sendMsg("Test Message");
I also have the following object defined and binded to the script as "javaobj":
public class TestConnection {
...
public void send(String message) {
// Code to send the string message via JMS
}
}
However, the Rhino engine complains with the following Exception. It seems to not like calling the javaobj's send method, for some reason.
javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: TypeError: Cannot find function send in object
function sendMsg(msg) {...}. (TestCase.js#3) in TestCase.js at line number 3
at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:224)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:212)
at com.foo.test.scenario.JavaScriptEngine.execute(JavaScriptEngine.java:56)
at com.foo.test.TestSuite.start(TestSuite.java:88)
at com.foo.test.TestSuite.main(TestSuite.java:41)
Caused by: sun.org.mozilla.javascript.internal.EcmaError: TypeError: Cannot find function send in object
function sendMsg(msg) {...}. (TestCase.js#3) in TestCase.js at line number 3
at sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3773)
at sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3751)
at sun.org.mozilla.javascript.internal.ScriptRuntime.typeError(ScriptRuntime.java:3779)
at sun.org.mozilla.javascript.internal.ScriptRuntime.typeError2(ScriptRuntime.java:3798)
at sun.org.mozilla.javascript.internal.ScriptRuntime.notFunctionError(ScriptRuntime.java:3869)
at sun.org.mozilla.javascript.internal.ScriptRuntime.getPropFunctionAndThisHelper(ScriptRuntime.java:2345)
at sun.org.mozilla.javascript.internal.ScriptRuntime.getPropFunctionAndThis(ScriptRuntime.java:2312)
at sun.org.mozilla.javascript.internal.Interpreter.interpretLoop(Interpreter.java:1524)
at sun.org.mozilla.javascript.internal.Interpreter.interpret(Interpreter.java:854)
at sun.org.mozilla.javascript.internal.InterpretedFunction.call(InterpretedFunction.java:164)
at sun.org.mozilla.javascript.internal.ContextFactory.doTopCall(ContextFactory.java:429)
at com.sun.script.javascript.RhinoScriptEngine$1.superDoTopCall(RhinoScriptEngine.java:116)
at com.sun.script.javascript.RhinoScriptEngine$1.doTopCall(RhinoScriptEngine.java:109)
at sun.org.mozilla.javascript.internal.ScriptRuntime.doTopCall(ScriptRuntime.java:3163)
at sun.org.mozilla.javascript.internal.InterpretedFunction.exec(InterpretedFunction.java:175)
at sun.org.mozilla.javascript.internal.Context.evaluateReader(Context.java:1159)
at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:214)
... 4 more
Has anyone ever encountered this type of issue with Rhino?
P.S. This question seems related, but no answer given as well (TypeError in Rhino: migration from Java 6 to Java 7)
Looks like I found my own answer. There was a name conflict between the Javascript function and the name of the binded Java object. Both having the same name, the engine tries to call a non-existent method on a Function object!
Silly me... :P

js function containing php executes when not called

I have the following code within the tag of my page:
<script>
function LogInOut()
{
// Get the current login status
alert("executing LogInOut");
$loginStatus = "<?php echo $_SESSION['login']; ?>";
if ($loginStatus == "true")
{
<?php
echo "<br />script function";
$_SESSION['login'] = "false";
session_destroy();
?>
document.getElementById("loginState").innerHTML = "login";
}
else
{
window.location = 'login.php';
}
}
</script>
I find that the php code executes when the page loads. The function (for debugging) is NEVER called yet the php code executes while none of the rest of the script executes! Can anyone clarify why this could be happening?
thank you,
Shimon
Classic case of mixing Javascript, a client side language, with PHP, a server side language. They run at two different locations and that being said this will never be possible.
PHP runs before javascript and if your trying to mix it with javascript, use it to echo dynamic data. eg:
var logged_in = <?=($_SESSION['login'] ? 'true' : 'false')?> ;
Javascript runs within the browser and after PHP, do not use php code thinking it will run inside of the browser
You will need something to call the function
In your case, call it when page is ready.
$(document).ready(function(){
LogInOut();
});
Or using a console for modern browser type in:
LogInOut();

how to use java to get a js file and execute it and then get the result

How can I use java to get a js file located on a web server, then execute the function in the js file and get the result and use the result in java.
Can you guys give me some code snippet? Great thanks.
You can use the scripting engine built into Java:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public static void main(String[] args) throws Exception {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
Object result = engine.eval("my-java-script-code")
System.out.println("Result returned by Javascript is: " + result);
}
Here is a more elaborate example.
There's three steps to this process:
Fetch the JS file from the server.
Execute some JS function from the file.
Extract the result.
The first step is fairly simple, there are lots of HTTP libraries in Java that will do this - you effectively want to emulate the simple functionality of something like wget or curl. The exact manner in which you do this will vary depending on what format you want the JS file in for the next step, but the process to get hold of the byte stream is straightforward.
The second step will require executing the JS in a Javascript engine. Java itself cannot interpret Javascript, so you'd need to obtain an engine to run it in - Rhino is a common choice for this. Since you'd need to run this outside of Java, you'll likely have to spawn a process for execution in Rhino using ProcessBuilder. Additionally, depending on the format of the Javascript you might need to create your own "wrapper" javascript that functions like a main class in Java and calls the method in question.
Finally you need to get the result out - obviously you don't have direct access to JavaScript objects from your Java program. The easiest way is going to be for the JS program to print the result to standard out (possibly serialising as something like JSON depending on the complexity of the object), which is being streamed directly to your Java app due to the way you launched the Rhino process. This could be another job for your JS wrapper script, if any. Otherwise, if the JS function has observable side effects (creates a file/modifies a database) then you'll be able to query those directly from Java.
Job done.
I hope you realise this question is far too vague to get full answers. Asking the public to design an entire system goes beyond the point where you'll get useful, actionable responses.
There are plenty of examples on the web of how to download a file from a URL.
Suns version of the JDK and JRE includes the Mozilla Rhino scripting engine.
Assuming you have stored the contents of the javascript file in a string called 'script', you can execute scripts as follows
String result = null;
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
try {
jsEngine.eval(script);
result = jsEngine.get("result")
} catch (ScriptException ex) {
ex.printStackTrace();
}
The result will be extracted from the engine and stored in the 'result' variable.
The is a tutorial on scripting in Java that might be useful.

Categories