I want to make a button in NetBeans, that when clicked, will open a webpage, wait until the webpage loads, and logs in to that site. I have some code here, but I am not sure what to do after this:
javascript:(function (){
window.open("http://www.stackoverflow.com");
object.onload="LoginToThisSite"
})();
I also have a bookmarklet that logs you in to the site automatically, I am just not sure how to tie that in to the button.
Here is the code I have in NetBeans for the button:
public void actionPerformed(ActionEvent evt) {
String cmd = evt.getActionCommand();
if (cmd == "POST") {
try {
String url = "http://www.stackoverflow.com";
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
}
catch (java.io.IOException e) {
System.out.println("Couldn't open browser...");
}
}
}
I would appreciate all the help I can get, as I am horrible at coding in Java.
Use $(document).ready()
This function would excute after document is loaded
(Jquery)
since you don't have access to the website you are trying to authenticate with the best you can do is to wait an arbitrary length of time (in this case 30000 milliseconds):
<body onload="setTimeout(authenticationAttempt,30000);">
<script>
function authenticationAttempt() {
// add your code to login here
alert('after 30 seconds i assume the page is loaded');
}
</script>
</body>
here is a jsfiddle example which allows 5 seconds for bing.com to load before running additional code.
http://jsfiddle.net/DaveAlger/CFLh2/
if the website you are trying to authenticate with is public you should post a link to it because i still think what you are attempting will not be allowed unless you have access to change the code on the school website.
Related
Goal: alert pop up. whether it's shown or not, I want it to continue. if it shows, have to select the checkbox, and hit continue. if not, ignore.
Blocker: if alert shows, it will handle the action and dialog will be closed. but when it's not, selenium hangs there without handling condition when it's not shown.
background: I use UFT before, maybe my logic could be wrong.
the pop up is application alert(not systems), so assumed "switch to(),accept()/dismiss() won't work. and I will add handle alert right after login and within the login method below.
Selenium framework background. : we use selenium maven framework, serenity BDD. object is set at the beginning of the page. and serenity.properties handle the time out default and so on.
Pop up objects (if it appears):
#FindBy(xpath = "//input[#id='notification-ack']")
private WebElement PcoNoticeChbx; //this is a check box, needs to be checked
#FindBy(xpath = "//button[contains(.,'Continue')]")
private WebElement PcoNoticeContinueBtn;//button to close the alert
*Log in method *
public void loginIntoExtApplication(String baseURL, String loginURL, String uId, String pwd, String extAppEnv)throws Exception {
gotoExtLoginPage(baseURL, loginURL);
enterLoginCredential(uId, pwd);
openAt("https://" + extAppEnv + ".programportaltest.hrsa.gov/sdms-
extranet/index.xhtml");
My Approaches:
//1.
if (PcoNoticeChbx!=null) {
PcoNoticeChbx.click();
PcoNoticeContinueBtn.click();
} else {
System.out.println("Dialog didn't display, no need any action");
}
//2. hanged here after login actions.
if(!getDriver().findElements(By.xpath("//*[#id='submit']")).isEmpty()){
PcoNoticeChbx.click();
PcoNoticeContinueBtn.click();
}
else {
System.out.println("Dialog didn't display, no need any action");
}
//3. added to watch doesn't work, it shows pending, below code failed too. I ran my Maven in Junit in debug mode. it used to work fine. but watch elements always show (pending)..
boolean isPresent = getDriver().findElements(By.id("noticebox")).size() >0
System.out.println("the diaolog exist= " + isPresent);
//4. even tried the try-catch method.
try{
PcoNoticeChbx.click();
PcoNoticeContinueBtn.click();
}catch (Exception e){
// Printing logs for my report
Log.error("Report Category button element is not found.");
// After doing my work, now i want to stop my test case
throw(e);
}
return;
}
//5. tried list webelemets:
List temp = webdriver.findElements(org.openqa.selenium.By.id("noticebox"));
if (temp.Count > 0 && temp[0].Displayed) {
// script to execute if element is found
} else {
// continue the test
}
//6. and below
if (!WebDriver.findElements(By.xpath("//*[#id='submit']")).isEmpty()==true);
{
//handle the dialog
}
else{
//continue
}
// 7.tried with a boolean value, but it also hangs on here first steps
boolean Nbox = PcoNoticeChbx.isDisplayed(); {
if (Nbox==false)
{
System.out.println("Dialog didn't display, no need any action");
}
else if (Nbox==true) {
PcoNoticeChbx.click() ;
PcoNoticeContinueBtn.click();
}
If this is like the popups that I've dealt with they work like this:
Customer comes to site and the site checks for the existence of a cookie. If that cookie exists, the popup is never launched (ideal state). If that cookie does NOT exist (typical state), after a specified period of time a popup appears.
Customer dismisses the popup and a cookie is created with an expiration time
Once that expiration time passes, the cookie expires and the popup will fire again
You need to do some investigation and find the cookie that is created once the popup is dismissed. Clear your cache, browse to the site, and note all the cookies that exist. Wait for the popup and dismiss it. Now find the cookie that was just created and examine it. This is the cookie you need to create. There are a lot of tutorials on creating cookies. It's pretty straightforward.
Once you learn how to create the cookie, you add it to your script as described below:
Navigate to some page on the domain that you know doesn't exist, e.g. www.domain.com/some404page. We do this because it won't trigger the popup countdown and we need to be on the domain to create the cookie.
Create the cookie
Do your normal test
No more popups.
Solution found for my case.
this maybe very easy. but takes some times for me to research. hopefully it will help you.
after use of many methods, for this javascripts confirmation alert. i have used below method. all of help of .CurrentlyVisible() method. because this one, and i guess only this one will give you result even when the element does not exist or null..
if (element(NoticeContinueBtn).**isCurrentlyVisible**()==true) {
PcoNoticeChbx.click();
PcoNoticeContinueBtn.click();
//else just continue
}
I've been testing HtmlUnit with a few sites; in all these sites,they have
elements such as a radio button or checkbox that when you click, then your
profile on that site is updated; you don't need to submit a form or
anything. But when I take the exact same actions with HtmlUnit, my profile
on the server is not really updated. Do I have to do something special
such as synchronizing the local copy of the page that HtmlUnit has with the
server so that the server sees the change? As an example, I have added my
code for switching my resume on a website from private/public and vice
versa. When I visit the page on a browser, all I have to do is click one
of the two radio buttons to make the resume public/private; but when I do
the same on HtmlUnit, and then go and visit the page on a browser to check, I can see that the information on the server hasn't been changed. I've
included my code below. Note that I have another method which logs in to
the site, and I know that I login correctly. Given this is happening
with my sites for me, I thought maybe there is something like synchronizing with the server that I'm not doing.
=====================================
public void update(String urlOfThePage)
{
// First, declare any element name or xapth that you are going to
use. String xpathOfIsPublicRadioButton = "//input[#id='privacy_show']";
String xpathOfIsPrivateRadioButton = "//input[#id='privacy_hide']";
// Get the first page
try
{
final HtmlPage resumePage = (HtmlPage) webclient.getPage(urlOfThePage);
CrawlerUtility.savePage(resumePage, "resumePage");
final HtmlRadioButtonInput makePublicRadioButton =
(HtmlRadioButtonInput)
resumePage.getFirstByXPath(xpathOfIsPublicRadioButton);
final HtmlRadioButtonInput makePrivateRadioButton =
(HtmlRadioButtonInput)
resumePage.getFirstByXPath(xpathOfIsPrivateRadioButton);
Page result = null;
if (isProfilePublic())
{
result = makePrivateRadioButton.click();
System.out.println("The Profile is changed to private
now.");
Thread.sleep(60000);
}
else
{
result = makePublicRadioButton.click();
System.out.println("The Profile is changed to public now.");
Thread.sleep(60000);
}
}
catch (Throwable e)
{
e.printStackTrace();
}//End of try/catch block.
}//End of update().
If you don't submit a form, then you may be using AJAX behind the scenes to send data to the server. HTML unit won't send the same to the server since it will not process the AJAX requests. What you need is something more sophisticated such as Sikuli http://www.sikuli.org which actually clicks on elements on your webpage in the exact same way a user does. You can also try Selenium (http://www.seleniumhq.org/) which is specific to web browsers.
I am trying to create a screen for a blackberry 5.0+ app that has a banner at the top and then a Browserfield underneath that views an external site. The banner is hosted on one site and the content for the BrowserField is hosted on another.
Originally I tried using 2 BrowserFields but had issues when several devices did not display the banner and only showed the content underneath. Furthermore when another screen with the same setup was displayed the app would crash with an IllegalStateException. I did a bit of research and it seems that BrowserField seems to have some trouble when several instances of it exist at once.
So in order to get around this issue I have combined both BrowserFields into one, using the frame tag in html, with the hopes of displaying the Banner ad in the first frame and the content underneath in the second frame.
The html I made works in a normal browser:
<!DOCTYPE html>
<html>
<frameset rows="10%,90%">
<frame scrolling="no" src="http://4.bp.blogspot.com/_CZ1HhhanNgc/TI0xscVLW8I/AAAAAAAABps/sfeO4E3234k/s1600/head-mp-700x88.jpg" noresize="noresize" frameborder="0">
<frame src="http://www.penny-arcade.com" frameborder="0">
</frameset>
</html>
What I am doing is reading the html in as text, removing the \n and \rs and then putting it in the following method: browserField.displayContent(html,"http://localhost");
This method is supposed to display the html in the browser, but instead on the simulator I get this:
On the device I get a blank screen. I don't know whats going on with the displayContent() method, so I would assume that it doesn't allow external sites? I don't really know what my options are from this point on. Is there some kind of fix for this, some library that I can use or some other way to implement this?
Edit:
So #Nate suggested a change to the DOCTYPE tag, and posted a screenshot of the html working. However I did this and I still get the same results, so I am going to post the code I'm using to make the screen. Here it is:
public final class MyScreen extends MainScreen
{
/**
* Creates a new MyScreen object
*/
private BrowserField browserField;
public MyScreen()
{
// Set the displayed title of the screen
setTitle("MyTitle");
BrowserFieldConfig config = new BrowserFieldConfig();
config.setProperty(BrowserFieldConfig.VIEWPORT_WIDTH, new Integer(Display.getWidth()));
config.setProperty(BrowserFieldConfig.NAVIGATION_MODE,
BrowserFieldConfig.NAVIGATION_MODE_POINTER);
config.setProperty(BrowserFieldConfig.INITIAL_SCALE, new Float(1.0));
config.setProperty(BrowserFieldConfig.USER_SCALABLE, Boolean.FALSE);
//supposed to prevent InvalidStateException from refreshing sometimes
ProtocolController eventsProtocolController = new ProtocolController(browserField)
{
public void handleNavigationRequest(BrowserFieldRequest request) throws Exception
{
browserField.setFocus();
super.handleNavigationRequest(request);
}
};
config.setProperty(BrowserFieldConfig.CONTROLLER, eventsProtocolController);
browserField = new BrowserField(config);
try
{
String embeddedLinkFrame = readTextFile("frame.html");
browserField.displayContent(embeddedLinkFrame, "http://localhost");
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
add(browserField);
}
public String readTextFile(String fName)
{
String result = null;
DataInputStream is = null;
try
{
is = new DataInputStream(getClass().getResourceAsStream("/" + fName));
byte[] data = IOUtilities.streamToBytes(is);
result = new String(data);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
if (null != is)
is.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
return result;
}
}
Ok, my apologies for the first answer. I think DOCTYPE was a red herring (but I didn't have your Java code at the time).
I see a few potential problems:
Network Connectivity
First, as is always the case, make sure you have network connectivity for your device, or simulator. That may include the MDS simulator running. You can always test connectivity with the normal Browser app, checking a website you know to be running. I believe that if you have a total lack of connectivity (i.e. network disabled), then you will get your frames showing just the text / URLs. However, I believe it will also have something like this:
Could not select proper Transport Descriptor for: http://www.penny-arcade.com
instead of showing null, as you show.
Adding BrowserField
Next, I think there is a problem with you asking the browser field to display content before you've added the field. Simply switch the order of those two lines of code to this:
add(browserField);
try
{
String embeddedLinkFrame = readTextFile("frame.html");
browserField.displayContent(embeddedLinkFrame, "http://localhost");
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
I believe the behaviour if you have these lines out of order, however, is just to get a blank browser field.
Viewport Properties
Lastly, I would not recommend setting page properties programmatically, as you've done. Although this is not going to keep your page from displaying, I'd recommend putting those properties in HTML meta elements:
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
</head>
Source: BlackBerry.com
Update: Protocol Controller
Unfortunately, my simulator is acting up, and declining to support hot-swap right now. So, it's hard for me to run many times, and collect decisive results. But, it looks to me like removing your ProtocolController object prevents this problem from happening for me. (maybe you can clarify why you're using the protocol controller in this situation?). If this answer was a motivation, you might look carefully at the poster's full comments about it's usefulness.
I know in scripting languages like Python that this is possible but I know that Java applets can't access other servers other than their own.
I don't know/think I can get this applet signed. Is there a way to use PHP to do what I want to accomplish?
I also know that this code will go to google.com
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
public class tesURL extends Applet implements ActionListener{
public void init(){
String link_Text = "google";
Button b = new Button(link_Text);
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent ae){
//get the button label
Button source = (Button)ae.getSource();
String link = "http://www."+source.getLabel()+".com";
try
{
AppletContext a = getAppletContext();
URL u = new URL(link);
// a.showDocument(u,"_blank");
// _blank to open page in new window
a.showDocument(u,"_self");
}
catch (MalformedURLException e){
System.out.println(e.getMessage());
}
}
}
That is assuming that source.getLabel() is "google"
But how would I get the source html of that page?
The source html is dynamic and is updated every few seconds or miliseconds. But, the html is also updated, so I can still read the dynamic content directly from the html. I already did this in vb.net, but now I need to port it to Java, but I can't figure out how to access a page's html source; that's why I'm asking.
AppletContext.showDocument opens a page in the browser, much like a hyperlink in HTML or a similar call in JavaScript would do. Under the Same Origin Policy you will not have access to this page if it is from a different site, even if the page is in an iframe.
Some sites may have a crossdomain.xml policy file that allows access if you were to read the contents of the java.net.URL directly. However, www.google.com appears to be using a restricted form that I don't believe is currently supported by the Java PlugIn.
Someone will probably suggest signing your applet, which turns off the "sandbox" security feature of Java. You would then need to persuade your users to trust your ability to publish safe signed code.
Hello I am looking for information on the close tab (not browser) event if there is one in java for a applet. I am wondering if there is an event for that or a way to check a way to check for that. I would like to just capture the event and make a little popup box , stating Your session will expire or something along those lines. Is that possible at all or to a point with java or Javascript?
UPDATE: okay with the information you guys pointed me into i was able to get information on a simple enough javascript. Now it is working fine in IE , Chrome and Firefox but for some reason Safari 5.1.7 isn't liking the code. Not sure why. Here is the code if it helps.
jQuery(function() {
var hiddenBtn = document.getElementById("javaform:browserCloseSubmit");
try{
opera.setOverrideHistoryNavigationMode('compatible');
history.navigationMode = 'compatible';
}catch(e){}
//Sends the information to the javaBean.java file.
function ReturnMessage()
{
return hiddenBtn.click();
}
//UnBind Function
function UnBindWindow()
{
jQuery(window).unbind('beforeunload', ReturnMessage);
}
//Bind Exit Message Dialogue
jQuery(window).bind('beforeunload', ReturnMessage);
});
You have the onBeforeUnload event you can catch in JavaScript. See here.
Use window.onbeforeunload
window.onbeforeunload = function () {
return "Are you sure you want to exit?";
};
Note that it will also end in Are you sure you want to leave this page (or are you sure you want to reload this page if you are reloading)