Opening a web browser and controlling it as a Virtual User - java

I am trying to open a browser and then simulate a user in Java. Previously I would have accomplished this with simple Applescript, with something like this
tell application "Safari"
activate
open location "http://google.co.uk"
delay 1
do JavaScript "
document.getElementById('gbqfq').value ='software is hard';
" in document 1
end tell
So it opens Safari, then types into Google's query box.
In Java, so far I have
import javax.script.*;
public class VirtualUser {
public static void main(String[] args) throws Exception {
Runtime.getRuntime().exec("open /Applications/Safari.app");
Thread.sleep(1000);
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
engine.eval("print('Hello World')");
}
}
Which opens Safari (Google homepage), and prints Hello World in the IDE (verification that JS is working within Java?)
In the Java example, how can I then further enter text into Google's search bar? And is utilising JavaScript within Java the best/only solution for this?

I've had some luck with Selenium in the past. It automates a browser and you can run commands exactly like you are describing. Definitely go check it out.

Related

How to press a keyboard key without a physical keyboard in selenium

I'm trying to build an automation script that will install a chrome extension.
On my local system (windows 10) all works fine while using Robot class with java, since I have a physical keyboard connected to my computer.
The problem is - when I try to run this automation on a virtual machine(Amazon EC2, windows server), the Robot class is not working because it doesn't detect a physical connection of a keyboard.
Is there any other way to simulate a keyboard stroke without a keyboard attached?
FYI, I have to use the keyboard because google install box is not part of the page and selenium wont recognize it.
I've tried the sendKeys function but it didn't work because it will affect only the webpage itself and not pop outside of the page
I believe you can use java robot functions to mimic the keyboard interactions.
Example:
package org.kodejava.example.awt;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class CreatingKeyboardEvent {
public static void main(String[] args) {
try {
Robot robot = new Robot();
// Create a three seconds delay.
robot.delay(3000);
// Generating key press event for writing the QWERTY letters
robot.keyPress(KeyEvent.VK_Q);
robot.keyPress(KeyEvent.VK_W);
robot.keyPress(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_R);
robot.keyPress(KeyEvent.VK_T);
robot.keyPress(KeyEvent.VK_Y);
} catch (AWTException e) {
e.printStackTrace();
}
}
}
I don't think you can do this with Selenium, cause it is meant to test webpages, not to automate a human-computer interaction.
If you want to automate a complex scheme like this, you may try a more complete solution, like UiPath :
https://www.uipath.com/
This is a solution meant for automation, so it will give you more tools to achieve your goal. It has a community edition which is free, and an active forum, so you should be able to handle it quickly !

Call Javascript Popup in java program

I'm try show Popup in java program(web).
I try ScriptEngine with javascript, nashorn but fail. Because alert,confirm, prompt is not method of js.
Code in java program:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(new FileReader("script.js"));
Invocable invocable = (Invocable) engine;
invocable.invokeFunction("openPopup", "ABC XYZ");
and in script.js:
function openPopup(str){
alert(str);
}
Run it, error show:
"alert" is undefined
Explanation
Opening a JavaScript popup in Java is not possible. The JavaScript Engine Nashorn does not provide this method. It usually is a functionality provided by browsers.
That is also why you are getting:
"alert" is undefined
Solution
You can open popup windows with different tools in Java, for example Swing or JavaFX. Those are tools with which you can create programs with graphical user interfaces (GUI), i.e. that have windows.
Here is an official tutorial by Oracle on how to create dialogs with Swing.
The relevant method for creating just a simple popup is:
JOptionPane.showMessageDialog(frame, "Hello world!");
Where frame is a reference to the window which should be the parent of this popup. However you can simply pass null for a quick and dirty popup:
JOptionPane.showMessageDialog(null, "Hello world!");
Just use the above code, import the JOptionPane and it should work:
import javax.swing.JOptionPane;
The class has more interesting methods to check out, like input dialogs. Here is its documentation.
The JavaFX solution is a bit more complicated as it requires you to setup the frame and handle several events.
You may check out this other question SO: Popup window with table view in JavaFX 2.0. It uses the designated class Popup (documentation).

Java GUI - Web Browser and Opening Link

I am creating a game and I made a Launcher. I have seen on other games made out of Java (Like MineCraft) have a webpage on the launcher. I was woundering how to put a webpage on a Java Swing GUI panel. I would also like to know how to open their browser up to a link with a button.
Thanks,
Blockquote
To open a url in the system's web browser you can use java.awt.Desktop.browse(URI). This allows you to keep your Java code platform independent, and even allows you to check to see if an operation is supported before trying to use it.
To load a web page within Java, I've had some success using the JavaFX WebView.
import java.awt.Desktop;
import java.net.URI;
class URLBrowsing
{
public static void main(String args[])
{
try
{
// Create Desktop object
Desktop d=Desktop.getDesktop();
// Browse a URL, for example www.facebook.com
d.browse(new URI("http://www.facebook.com"));
// This open facebook.com in your default browser.
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

Java SE: Open Web Page and Click a Button

I have a Java 7 program (using WebStart technology, for Windows 7/8 computers only).
I need to add a function so that my program clicks a button on a page with known URL (https).
Some people suggest WebKit SWT, but I went to their site and they say that the project was discontinued. (http://www.genuitec.com/about/labs.html)
Other people say that JxBrowser is the only option but it looks like it's over $1,300 which is crazy. (http://www.teamdev.com/jxbrowser/onlinedemo/)
I'm looking for something simple, free, lightweight, and able to open HTTPS link, parse HTML, access a button through DOM and click it. Perhaps some JavaScript too, in case there are JS handlers.
Thanks for your help.
You may be looking for HtmlUnit -- a "GUI-Less browser for Java programs".
Here's a sample code that opens google.com, searches for "htmlunit" using the form and prints the number of results.
import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;
public class HtmlUnitFormExample {
public static void main(String[] args) throws Exception {
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage("http://www.google.com");
HtmlInput searchBox = page.getElementByName("q");
searchBox.setValueAttribute("htmlunit");
HtmlSubmitInput googleSearchSubmitButton =
page.getElementByName("btnG"); // sometimes it's "btnK"
page=googleSearchSubmitButton.click();
HtmlDivision resultStatsDiv =
page.getFirstByXPath("//div[#id='resultStats']");
System.out.println(resultStatsDiv.asText()); // About 309,000 results
webClient.closeAllWindows();
}
}
Other options are:
Selenium: Will open a browser like Firefox and operate it.
Watij: Also will open a browser, but in its own window.
Jsoup: Good parser. No JavaScript, though.
Your question is kind of difficult to understand what you want. If you have a webstart app and want to open a link in the browser, you can use the java.awt.Desktop.getDesktop().browse(URI) method.
public void openLinkInBrowser(ActionEvent event){
try {
URI uri = new URI(WEB_ADDRESS);
java.awt.Desktop.getDesktop().browse(uri);
} catch (URISyntaxException | IOException e) {
//System.out.println("THROW::: make sure we handle browser error");
e.printStackTrace();
}
}

How to use HTML and CSS as a Java application GUI?

I want to design new Git client with a clean GUI.
Is it possible to use the power of HTML, CSS and JavaScript in a java application?
I would like to use Java + JGit for models, Java for controllers and HTML + CSS + JavaScript for views.
I don't want a client-server model. I would like to integrate Java and HTML nicely. A DOM event would fire events directly to a Java controller. This way it would be possible to create rich offline application.
You can embed web browser component into your Java Swing/JavaFX Desktop application that displays GUI built with HTML5+CSS+JavaScript. You can see an article that describes how to do this at https://jxbrowser-support.teamdev.com/docs/tutorials/cross-desktop-apps.html
One of the Java Swing/JavaFX libraries that allows embedding Chromium into Java applications is JxBrowser. Using JxBrowser API you can load any web page and work with its DOM and JavaScript. You can even call Java methods from JavaScript code and vice versa. For example:
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.JSFunctionCallback;
import com.teamdev.jxbrowser.chromium.JSObject;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
public class JavaScriptJavaSample {
public static void main(String[] args) {
Browser browser = new Browser();
browser.addLoadListener(new LoadAdapter() {
#Override
public void onFinishLoadingFrame(FinishLoadingEvent event) {
if (event.isMainFrame()) {
Browser browser = event.getBrowser();
JSObject window = (JSObject)
browser.executeJavaScriptAndReturnValue("window");
window.setProperty("MyFunction", new JSFunctionCallback() {
#Override
public Object invoke(Object... args) {
for (Object arg : args) {
System.out.println("arg = " + arg);
}
return "Hello!";
}
});
JSValue returnValue = browser.executeJavaScriptAndReturnValue(
"MyFunction('Hello JxBrowser!', 1, 2, 3, true);");
System.out.println("return value = " + returnValue);
}
}
});
browser.loadURL("about:blank");
}
}
It's not really feasible. Rich clients in Java are done using Swing or SWT.
If you want to use HTML/CSS for your user interface, you need to use the server/client model. It can be as simple as creating a local server and launching a browser that connects to it, but it would still be that model.
If you absolutely need to have HTML/CSS as your UI framework and can't go to a server/client model, your best bet is probably looking at something like Google Native Client, but that uses C/C++ bindings on the backend. I haven't used Native Client so I can't personally give much more information on that front.
Edit to add:
One option is to embed a native browser into your Swing app using something like: http://djproject.sourceforge.net/ns/
There are some pure Java HTML renderers, however, they most likely won't be fully HTML5/CSS3 compliant, let alone possibly have Javascript bugs as well.
See here for some of those options: Pure Java HTML viewer/renderer for use in a Scrollable pane
Like #Reverand Gonzo says, you will need some form of server/client. But you could easily embed a Jetty server into a Java app and then use GWT for your client code.
You can bring in the power of HTML,CSS,JavaScript into your Swing app using JFXPanel to embed JavaFX WebView. Have a look at the SimpleSwingBrowser demo in this link:https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/swing-fx-interoperability.htm
WebView allows to call JavaScript functions from Java and vice versa. It is also a nice way to enhance your legacy Java app with web technologies.
JavaFX 2.2 brought this functionality to providing a user interface component (GUI) that has web view and full browsing functionality.
For more details, see Adding HTML Content to JavaFX Applications.
Use Angular.js with HTML and rest of the things as same in Java, just use classes for business logic, no need to write code for awt/swing. Angular with spring boot are rapid development in Java for webapp with less code in Java without swing use to create best webapp .

Categories

Resources