I need to access the value of div element inside an iframe from java code. The iframe is on a web browser and java code is on local server. I need this to test the values in iframe. I am new in coding/automation, any suggestion on how this can be done will be helpful. I found on net how to access through JS but i need to get the values in my java code. I am not using selenium web driver but original browser.
Any suggestion/pointer will be helpful, Thanks SOF!!
If you have solution in JS then you can use the Java Scripting API
Below the basic example:
import javax.script.*;
public class EvalScript {
public static void main(String[] args) throws Exception {
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// evaluate JavaScript code from String
engine.eval("print('Hello, World')");
}
}
Related
I previously asked this question on StackExchange. Because it was put on hold, I'm following the comments and asking about how to fix this instead. To avoid repeating myself and copy pasting an explanation, please read the previous question I asked for the full details.
I'm trying to write my own custom ScriptEngine for Java. I tried extending the AbstractScriptEngine and implementing ScriptEngineFactory and filling out all the bare minimum required methods just to test if I'd be able to at least start working with scripts. (See the code HERE) When I ran the following code...
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension("sbs"); // <- THIS LINE HERE
System.out.println(engine);
try {
System.out.println(engine.eval("STRING!"));
} catch (ScriptException e) {
e.printStackTrace();
}
The manager.getEngineByExtension("sbs"); method returns null. I have also tried using getEngineByMimeType("text/SandboxScript"); as well as getEngineByName("SandboxScript"); but none of these have worked.
Is there something I set up incorrectly?
The lookup of custom script engines is via the service provider mechanism (see http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Service%20Provider), so this must be set up to be able to look up your class by name. In you project's META-INF directory, create folder named 'services' if one does not exist. Within this folder create a file named 'javax.script.ServiceEngineFactory' containing the line of your package/class
me.gamefreak0.ss.SandboxServiceEngineFactory
Presuming your project and META-INF is set up properly, your ScriptEngine should now be registered and you should be able to look it up by name.
The JSR223 Bindings class allows you to expose arbitrary Java objects to scripting languages. But they have to be objects. I would like to define a function quit() that can be called from the scripting environment that turns into quitObject.run() in Java. But JSR223 doesn't define the concept of a function object. Is there a language-independent way to do the following in Javascript, namely to take a Runnable() and create a function in the scripting environment?
static private Object asFunction(ScriptEngine engine, Runnable r)
throws ScriptException
{
final Bindings bindings = engine.createBindings();
bindings.put("r", r);
return engine.eval(
"(function (r) { var f = function() { r.run(); }; return f;})(r)",
bindings);
}
Runnable quitObject = /* get/create a Runnable here */
Bindings bindings = engine.createBindings();
bindings.put("quit", asFunction(engine, quitObject));
With the builtin Javascript support for JSR223 this creates a sun.org.mozilla.javascript.internal.InterpretedFunction which does what I want. But it obviously won't work in Jython or whatever, and I'd like to make this language-independent.
I don't want my script users to have to type quitObject.run() as that's clumsy, and I don't want to parse script input to find quit() as it could be buried within other code.
If you look at javascript engine source code you'll find how oracle/sun implemented 2 functions (print, and println) which are magically (or not so magically) present when you fire up your engine.
Those function are 'scripted' , which is more or less what you did.
What I would do is : load and evaluate a bootstrap.[language_extension] before evaluating any other input in the new context.
You could easily create such scripts for each language you intend to support.
I try to get a dynamic page from URL. I am working in Java. I have done this using Selenium, but it takes lots of time. As it takes time to invoke driver of Selenium. That's why I shifted to HtmlUnit, as it is GUILess Browser. But my HtmlUnit implementation shows some exception.
Question :-
How can I correct my HtmlUnit implementation.
Is the page produced by Selenium is simiar to the page produced by HtmlUnit? [ Both are dynamic or not? ]
My selenium code is :-
public static void main(String[] args) throws IOException {
// Selenium
WebDriver driver = new FirefoxDriver();
driver.get("ANY URL HERE");
String html_content = driver.getPageSource();
driver.close();
// Jsoup makes DOM here by parsing HTML content
Document doc = Jsoup.parse(html_content);
// OPERATIONS USING DOM TREE
}
HtmlUnit code:-
package XXX.YYY.ZZZ.Template_Matching;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.junit.Assert;
import org.junit.Test;
public class HtmlUnit {
public static void main(String[] args) throws Exception {
//HtmlUnit htmlUnit = new HtmlUnit();
//htmlUnit.homePage();
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.jabong.com/women/clothing/womens-tops/?source=women-leftnav");
String textSource = currentPage.asText();
System.out.println(textSource);
}
}
It shows exception :-
1: How can I correct my HtmlUnit implaementation.
Looking at the stack trace, it seems to be saying that the javascript engine executed some javascript that tried to access an attribute on a Javascript "undefined" value. If it is correct, that would be a bug in the javascript you are testing, not in the HtmlUnit code.
2: Is the page produced by Selenium is simiar to the page produced by HtmlUnit?
That does not make sense. Neither Selenium or HtmlUnit "produces" a page. The page is produced by the serve code you are testing.
If you are asking if HtmlUnit is capable of dealing with code that has embedded Javascript ... there is clear evidence in the stacktrace that it is trying to execute the Javascript.
I want to create a website with a game in applet form.
I want to use the highscores that people get in the game to show up on a leaderboard on the website?
How is this achievable?
Thanks
That can be done with JSObject, basically you pass information between Javascript and Java.
Example based on the documentation
.
Let's say this is your Java Applet, the netscape.javascript.* library is used to call the Plugin container of your browser (the window your Java Applet runs in) to pass information to, or from it. This is example is from the documentation, you can change the version to your preferred JDK version to whatever version you use.
import netscape.javascript.*;
import java.applet.*;
import java.awt.*;
class MyApplet extends Applet {
public void init() {
// requesting the JSObject
JSObject win = JSObject.getWindow(this);
// here you call a javascript function
win.call("myJavscriptFunction", null);
// if you wish to pass an argument to the javascript function,
// do the following
String myString = "World!";
final Object[] args = { myString };
win.call("myJavascriptFunction2()", args);
}
}
I will use the EMBED tag as an example, but the OBJECT (IE etc) tag can used also (see documentation in the link on top). The most important property you should not forget, is enabling MAYSCRIPT=true
<EMBED type="application/x-java-applet;version=1.3" width="200"
height="200" align="baseline" code="XYZApp.class"
codebase="html/" model="models/HyaluronicAcid.xyz" MAYSCRIPT=true
pluginspage="http://java.sun.com/products/plugin/1.3/plugin-install.html">
<NOEMBED>
No JDK 1.3 support for APPLET!!
</NOEMBED>
</EMBED>
Now the javascript function in your HTML/PHP file
<script text="text/javascript">
function myJavascriptFunction() {
alert("Hello!");
}
/**
* with argument
*/
function myJavascriptFunction2(myString) {
alert("Hello "+myString);
// will produce "Hello World!";
}
</script>
reference: java.sun.com/products/plugin/1.3/docs/jsobject
i think you should save all the highscores in database
use that scores using php or other language
Your applet is allowed to call URLs on originating server. This can be used to save higscores.
like code:
public static void main(String[] args) throws Exception {
String content="<HTML>"
+"<HEAD><TITLE>title</TITLE></HEAD>"
+"<BODY>"
+"<script>var jsvar=123;</script>"
+"</div>"
+"</BODY>"
+"</HTML>"
;
}
in this case,how to get jsvar variable value?
thanks for help :)
If you want to execute JavaScript code in Java, You can use scripting API of Java 6 and Java 6 is included with Mozilla Rhino engine.
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
jsEngine.eval("jsvar = 123");
System.out.println(jsEngine.get("jsvar")); //prints 123.0
Reference: http://download-llnw.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html
Seems to me that this is backward. If you are serving the page then you already have the value on the server. I would inject the value from Java into JavaScript not the other way around.
In fact, you're asking something that requires a browser. As a consequence, you may have to take a look at HtmlUnit, which could solve your issue.
However, were you to directly run pure javascript code from Java, you would have better using a Javascript interpreter like Rhino (I think).