Unable to hold on an element on mouse hover - eclipse

There is a mouse hover drop-down where the drop-down appears on hover and disappears if the mouse pointer is moved way from the drop-down. I tried using "Actions" class to hover on the drop-down element but i cannot see the drop-down after the mouse hover is performed. The drop-down doesn't stay till the next action is performed.
Is there any way where there is a wait after the hover is performed so that the drop-down appears for a longer time in order to select/click elements from the drop-down?
Code:
driver= new ChromeDriver();
driver.get("w3schools.com/howto/howto_css_dropdown.asp");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
WebElement element = driver.findElement(By.xpath(".//*#id='main']/div[3]/button")‌​);
Actions action= new Actions(driver);
action.moveToElement(element).perform();
Thread.sleep(5000);
Environment:
Chrome version: 56.0.2924.87 (64-bit)
Chrome driver: 2.27

Use same code that you wrote for mouse hover action and try following solution before mouse hover action.
Keep mouse cursor on task bar.
OR
Move mouse cursor at (0, 0) browser location.

After perform() you need to traverse through the elements.
Here is the working code:
package demo;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class MouseHoverDemo_w3school {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.w3schools.com/howto/howto_css_dropdown.asp");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement ele = driver.findElement(By.xpath(".//div[#class='dropdown dropdown2']/button"));
Actions act = new Actions(driver);
act.moveToElement(ele).perform();
List<WebElement> links = driver.findElements(By.xpath(".//div[#class='dropdown-content']/a"));
int total_count = links.size();
for (int i=0; i<total_count; i++)
{
WebElement element = links.get(i);
String text = element.getAttribute("innerHTML");
System.out.println("Link Name is : "+text);
}
driver.quit();
}
}
Let me know if this answers your question.

Related

Make jxBrowser open popups in the current window instead of "popping up"

How to set jxBrowser to open links that would pop-up in a new window to open on the calling page (or, at least, in a new tab)?
this is the call I think I have to override (it's the example):
//....
Engine engine = Engine.newInstance(
EngineOptions.newBuilder(
enderingMode.OFF_SCREEN ).enableIncognito().build()
Browser _browser = engine.newBrowser();
//this won't even compile
_browser.set(
OpenPopupCallback.class,
(params) -> {
// Access the created popup.
Browser popup = params.popupBrowser();
_browser.navigation().loadUrl(params.targetUrl());
return Response.proceed();
});
_browser.navigation().loadUrl("http://www.stackoverflow.com");
This is how I call it in my jfx but won't even compile, the code without this call works (opens a browser).
Update, given the nature of the popup I tried to rewrite javascript function (window.open) itself to force name to _parent.
This by running on every navigation the code
String the Javascript = "window.open = function (open) {return function (url, name, features{ console.log("open wrapper");return open.call(window, url, '_parent', features);};}(window.open);"
I thaught I couldn achieve this by
_browser.frames().get(0).executeJavaScript(theJavascript);
But in the remote console, I can't even see the log message ("open wrapper").
I double-checked the same code and it works if copy-pasted in the remote consolle.
What am I missing?
Here's complete JavaFX example that demonstrates how to open popup's URL in the main Browser instance and suppress popup:
import static com.teamdev.jxbrowser.engine.RenderingMode.OFF_SCREEN;
import com.teamdev.jxbrowser.browser.Browser;
import com.teamdev.jxbrowser.browser.callback.CreatePopupCallback;
import com.teamdev.jxbrowser.browser.callback.CreatePopupCallback.Response;
import com.teamdev.jxbrowser.engine.Engine;
import com.teamdev.jxbrowser.view.javafx.BrowserView;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public final class SmokeTest extends Application {
#Override
public void start(Stage primaryStage) {
// Creating and running Chromium engine.
Engine engine = Engine.newInstance(OFF_SCREEN);
Browser browser = engine.newBrowser();
browser.set(CreatePopupCallback.class, params -> {
browser.navigation().loadUrl(params.targetUrl());
return Response.suppress();
});
// Creating UI component for rendering web content
// loaded in the given Browser instance.
BrowserView view = BrowserView.newInstance(browser);
BorderPane root = new BorderPane(view);
Scene scene = new Scene(root, 1280, 900);
primaryStage.setTitle("Hello World");
primaryStage.setScene(scene);
primaryStage.show();
browser.navigation().loadUrl(
"https://www.encodedna.com/javascript/demo/open-new-window-using-javascript-method.htm");
// Close the engine when stage is about to close.
primaryStage.setOnCloseRequest(event -> engine.close());
}
}
Run this program and click a button that displays popup. You will see that popup is not displayed and its URL is loaded in the main Browser.

How to write selenium webdriver automation script for Facebook logout?

I tried this code. Its automating the browser, logging in successfully but I'm not able to logout successfully. Please Help.
public class fb {
public static void main(String args[])
{
WebDriver driver = new FirefoxDriver();
driver.get("https://facebook.com");
driver.manage().window().maximize();
driver.findElement(By.xpath(".//*[#id='email']")).sendKeys("your email");
driver.findElement(By.xpath(".//*[#id='pass']")).sendKeys("your password");
driver.findElement(By.xpath(".//*[#id='u_0_n']")).click();
driver.findElement(By.xpath(".//*[#id='userNavigationLabel']")).click();
driver.findElement(By.id("u_7_2")).click();// for logout-> button.But not working.
Automation Script for FaceBook Login and logout:
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.manage().window().maximize();
driver.findElement(By.xpath(".//*[#id='email']")).sendKeys("your email");
driver.findElement(By.xpath(".//*[#id='pass']")).sendKeys("your password");
//click for login
driver.findElement(By.xpath("//label[#id='loginbutton']/input")).click();
//Mouse over on logOut drop down menu icon,then click logout
WebElement mouseOverEle = driver.findElement(By.id("pageLoginAnchor"));
Actions actions = new Actions(driver);
actions.moveToElement(mouseOverEle).click().perform();
//click for logout
driver.findElement(By.xpath("//input[#value='Log Out']")).click();
Try Using the below code to click on the log out button
//wait for the userNavigationLabel to load fully any wait techniques implicit or explicit for sample i have used Thread.sleep although it is not recommended
Thread.sleep(3000);
JavascriptExecutor js = (JavascriptExecutor) driver;
String script = "var forms = document.getElementsByTagName('form');for (var i = 0; i < forms.length; i++) { if(forms[i].getAttribute('action')=='https://www.facebook.com/logout.php'){forms[i].submit();}}";
js.executeScript(script);
In the above code i have used javascript to click on the logout button...i tested it on the browser console it is working fine
Hope this helps you.....Kindly get back if you have any queries
try:
lsb=browser.find_element_by_xpath('//*[#id="pageLoginAnchor"]')
lsb.click()
time.sleep(5)
mlb=browser.find_element_by_xpath('//*[#id="u_d_3"]/div/div/div[1]/div/div/ul/li[16]')
time.sleep(2)
mlb.click()
inputElement33 = browser.find_element_by_name('pass').is_displayed()
print("Looged out")
except:
print("Cannot logout")
// Enter you Email id
dr.findElement(By.xpath(".//*[#id='email']")).sendKeys("YorEmailID");
// Enter you Password
dr.findElement(By.xpath(".//*[#id='pass']")).sendKeys("YourPassword");
//click for login
dr.findElement(By.xpath("//label[#id='loginbutton']/input")).click();
dr.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// Click for Alert
dr.findElement(By.className("_3ixn")).click();
//Click for Navigation Label
dr.findElement(By.xpath(".//*[#id='userNavigationLabel']")).click();
dr.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Click for Lout Button
dr.findElement(By.xpath("//a[contains(#data-gt,'menu_logout')]")).click();
Replace your logout button click with this.
//Wait for button appear
WebDriverWait wait = new WebDriverWait(driver,TimeSpan.FromSeconds(4));
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//a[.='Log out']")));
//Click it by xpath
driver.FindElement(By.XPath("//a[.='Log out']")).Click();
Or:
//Wait for button appear
WebDriverWait wait = new WebDriverWait(driver,TimeSpan.FromSeconds(4));
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//a[.='Log out']")));
//Click it by JS
IJavaScriptExecutor js = ((IJavaScriptExecutor)driver);
IWebElement logout = driver.FindElement(By.XPath("//a[.='Log out']"));
js.ExecuteScript("arguments[0].click();", logout);
100% worked
**#Working script**
**#firefox can be used too instead of chrome**
**#sleep is necessary to give sufficient loading time**
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import NoSuchElementException
usr=input('Enter Email Id:')
pwd=input('Enter Password:')
driver = webdriver.Chrome()
driver.get('https://www.facebook.com/')
a = driver.find_element_by_id('email')
a.send_keys(usr)
b = driver.find_element_by_id('pass')
b.send_keys(pwd)
c = driver.find_element_by_id('loginbutton')
c.click()
sleep(20)
d= driver.find_element_by_id("userNavigationLabel")
d.click()
sleep(10)
e=driver.find_element_by_xpath("//a[contains(#data-gt,'menu_logout')]")
e.click()
sleep(5)
driver.quit()
There are duplicate objects in the Home page.Hence, to avoid confusion,Xpath can be written in combination of class names, which in our case is,
//div[#class='uiScrollableAreaBody']/following::div[#class='uiScrollableAreaContent']/following::ul/li
Get the maximum number of <li> tags in the <ul> as follows ,
List<WebElement> li = driver.findElements(By.xpath("//div[#class='uiScrollableAreaBody']/following::div[#class='uiScrollableAreaContent']/following::ul/li"));
System.out.println("Size:"+li.size());
The Log out button will always be the last option, inspite of any changes to the list , hence append the last index to the xpath and click on it ,
String logOutBtn = "//div[#class='uiScrollableAreaBody']/following::div[#class='uiScrollableAreaContent']/following::ul/li[" + li.size() + "]";
driver.findElement(By.xpath(logOutBtn)).click(); -- Clicking on log out button
Hope this helps ! Thank you ..
package package1;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class class1 {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\CloudLogic.Tech01\\Desktop\\Selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver drr = new ChromeDriver();
drr.get("https://www.facebook.com/");
drr.findElement(By.id("email")).sendKeys("emailId");
drr.findElement(By.id("pass")).sendKeys("********");
drr.findElement(By.xpath("//label[#id='loginbutton']")).click();
}
}

Disabling toolbar from icePDF viewer

I am trying a sample with icePDF . Everything is working fine but i need to disable the toolbar which appears at the top. i tried few things but its not working. Can some body please help me out with it. Below is my code.
//package XML.test;
package applet;
import java.util.ResourceBundle;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.icepdf.ri.common.ComponentKeyBinding;
import org.icepdf.ri.common.SwingController;
import org.icepdf.ri.common.SwingViewBuilder;
import org.icepdf.ri.util.PropertiesManager;
import org.icepdf.core.pobjects.fonts.*;
import org.icepdf.core.views.DocumentViewController;
import org.icepdf.core.*;
public class ViewerComponentExample
{
static void buildFrame(String filepath)
{
System.getProperties().put("org.icepdf.core.scaleImages", "false");
System.getProperties().put("org.icepdf.core.imageReference","smoothScaled");
System.getProperties().put("org.icepdf.core.target.dither", "VALUE_DITHER_DISABLE");
System.getProperties().put("org.icepdf.core.target.fractionalmetrics", "VALUE_FRACTIONALMETRICS_OFF");
System.getProperties().put("org.icepdf.core.target.interpolation", "VALUE_INTERPOLATION_NEAREST_ NEIGHBOR");
System.getProperties().put("org.icepdf.core.screen.interpolation", "VALUE_INTERPOLATION_NEAREST_NEIGHBOR");
System.getProperties().put("org.icepdf.core.awtFontLoading","true");
SwingController controller = new SwingController();
PropertiesManager properties = new PropertiesManager(System.getProperties(), ResourceBundle.getBundle(PropertiesManager.DEFAULT_MESSAGE_BUNDLE));
properties.setBoolean(PropertiesManager.PROPERTY_SHOW_TOOLBAR_ANNOTATION, Boolean.FALSE);
properties.setBoolean(PropertiesManager.PROPERTY_SHOW_TOOLBAR_FIT, Boolean.FALSE);
// Build a SwingViewFactory configured with the controller
SwingViewBuilder factory = new SwingViewBuilder(controller);
JPanel viewerComponentPanel = factory.buildViewerPanel();
// add copy keyboard command
ComponentKeyBinding.install(controller, viewerComponentPanel);
// add interactive mouse link annotation support via callback
controller.getDocumentViewController().setAnnotationCallback(
new org.icepdf.ri.common.MyAnnotationCallback(
controller.getDocumentViewController()));
// Use the factory to build a JPanel that is pre-configured
//with a complete, active Viewer UI.
// Create a JFrame to display the panel in
JFrame window = new JFrame("Metrics Wizard Help");
window.getContentPane().add(viewerComponentPanel);
window.pack();
window.setVisible(true);
controller.setPageFitMode(DocumentViewController.PAGE_FIT_WINDOW_WIDTH, false);
controller.openDocument(filepath);
}
public static void main(String args[])
{
String filepath = "C:/Users/vishalt/Workspaces/Eclipse 4.2 Java/htmltopdf/src/XML/output/SCB_TEST.pdf";
buildFrame(filepath);
}
}
private SwingController controller;
controller = new SwingController();
SwingViewBuilder viewBuilder = new SwingViewBuilder(controller, properties);
JPanel panel = viewBuilder.buildViewerPanel();
controller.setToolBarVisible(false);
You have to set the toolbar invisible because icePdf looks in the PDF-document for the property and overwrites your setting with default when there is no document opened!
There are two ways to this.
1) Follow this example to set all the toolbars to false.
http://www.icesoft.org/JForum/posts/list/17673.page#sthash.48ICrL2A.dpbs
2) You can modify or remove the toolbar by editing the source code for SwingViewBuilder.
Here is a link to the code: http://sventon.icesoft.org/svn/repos/repo/show//icepdf/trunk/icepdf/viewer/src/org/icepdf/ri/common/SwingViewBuilder.java?revision=34004
You probably want to comment out lines 481 - 483.
481 JToolBar toolBar = buildCompleteToolBar(embeddableComponent);
482 if (toolBar != null)
483 cp.add(toolBar, BorderLayout.NORTH)
Remove your import for SwingViewBuilder and create your own class with those lines commented out.

Eclipse - Opening editor programmatically causes focus problems

I'm having a bit of an issue with an eclipse plugin that I am working on. In this plugin, a special type of plugin-specific editor is often opened programmatically; this is triggered by various actions in various views/editors, but the code to open the editor is the same. The plugin-specific editors open fine; however, I've recently noticed that every time one of these editors is opened, a strange focus glitch happens:
When the editor is opened, it appears to receive focus, but if the previously active view/editor is clicked immediately after this, it does not take back focus. As soon as anything other than the previously active view/editor is clicked, the problem is instantly solved, and focus resumes normally.
As an example, say you choose a context menu option from the Package Explorer view, which causes an editor to open. The editor opens properly and appears to have focus. After this, you first click again on the Package Explorer, but it doesn't get focus (the editor still appears to have focus). You right-click on Package Explorer, but Package Explorer-specific context menu items do not appear. After this, you click on some other view and then on Package Explorer again. Now Package Explorer gets focus, as normal.
This is the code I'm using to open the editor:
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
final GraphEditorPart gp = (GraphEditorPart) page.openEditor(new NullEditorInput(), "editor.id");
After this, the editor is populated with some visuals, via the albireo SWT-AWT bridge (Not sure if this is relevant to the problem -- the class used for main editor elements is org.eclipse.albireo.core.SwingControl).
I thought perhaps the problem was that the editor wasn't "really" getting focus, or the previously active view wasn't "really" losing focus, so I tried adding the following line:
page.activate(gp);
However this didn't seem to change anything. Why this might happen?
package name:rcp_demo.Editor
class name: EmpCommand.java, EmployeeEditor.java and EmployeeEditorInput.java
package rcp_demo.Editor;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
public class EmpCommand extends AbstractHandler {
public static final String Id = "rcp_demo.Editor.EmpCommand";
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IWorkbenchPage page = window.getActivePage();
IEditorReference[] editors = page.getEditorReferences();
EmployeeEditorInput input = new EmployeeEditorInput();
//All Comments are easily understand
//public class EmployeeEditorInput implements IEditorInput{}
for (int i=0; i<editors.length; i++) {
//List out all Exist editor
//compare with EmployeeEditor.Id="rcp_demo.Editor.emp";
if (editors[i].getId().equals(EmployeeEditor.Id)) {
//public class EmployeeEditor extends EditorPart
//{
// public static final String Id="rcp_demo.Editor.emp";
// public void createPartControl(Composite parent) {.....}
//}
page.activate(editors[i].getEditor(true));
System.out.println("set focus an existing editor(Employee)");
return null;
}
}
try {
//open new Editor like EmployeeEditor.Id="rcp_demo.Editor.emp";
page.openEditor(input,EmployeeEditor.Id);
System.out.println("open Editor(Employee) ");
} catch (PartInitException e) {
e.printStackTrace();
}
return null;
}
}
Full describe this question and answer visit :
Eclipse RCP : have the same editor open in editor window

Windows 7 SWT COMBO Issue

I am facing an issue with the SWT Combo in my eclipse RCP application.
I will try explaining my issue with a use case for better understanding.
I have a combo box in a Eclipse RCP View with values say "A", "B","C","D" and i have a submit button beside it & a SWT table right below it.
Once the value is changed in the Combo and submit button is clicked, records would be displayed in the table.
Let us suppose "A" is selected by default and records of A are displayed in the table on view invocation.
Now I select "B" from the drop down and click submit. I see only the records of "A" in the table although the combo shows "B".
ONLY if I select "B" again from the combo and then click submit, "B"'s records gets displayed.
Now if I select C from the combo , only "B"'s records gets displayed.
Later, If i select D from the Combo , "C"'s records are displayed.
It seems that only the previous selections is processed and displayed rather than the current selection.
I am not facing this issue in Windows XP or prev versions of windows. I recently shifted to Windows 7 64-bit OS where I faced this issue.
Is this a known issue? Any help would be appreciated.
You use a drop down listener for storing the selected index. The drop down listener is triggered when the combo list drops down. At this time, the old selection is stored. If you select a new item in the list, the listener will not be triggered again. Though you always get the previous selected item index if you press the submit button later on.
To get what you want, you must use a selection listener instead of the drop down listener and all works fine. The selection listener is called when you select an item in the drop down list. Just replace SWT.DropDown with SWT.Selection.
filter.addListener(SWT.Selection, new Listener() {...});
Please find the sample code below
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
public class TestCombo {
private static String[] filterByText = new String[] {"A","B","C","D"};
static int index = 0;
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
Composite comp = new Composite(shell, SWT.NONE);
GridLayout layout = new GridLayout(2, false);
GridData gridData = new GridData(SWT.FILL,SWT.FILL,true,false);
comp.setLayout(layout);
comp.setLayoutData(gridData);
final Combo filter = new Combo (comp, SWT.READ_ONLY);
filter.setItems (filterByText );
filter.setText (filterByText[0]);
filter.setVisibleItemCount( filterByText.length );
filter.addListener(SWT.DROP_DOWN, new Listener() {
#Override
public void handleEvent(Event event) {
index = filter.getSelectionIndex();
}
});
Button submit = new Button (comp, SWT.PUSH);
submit.setText ("Submit");
GridData data = new GridData();
data.widthHint = 80;
submit.setLayoutData(data);
submit.addSelectionListener (new SelectionAdapter () {
public void widgetSelected(SelectionEvent e) {
System.out.println("The index is ==> "+index);
}
});
comp.pack();
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}