How to open a URL with a hash using Selenium? - javascript

I'm trying to test my Backbone.js web application with Selenium IDE.
Selenium can open my test case's initial URL so long as it's in a fresh browser window -- e.g. open /#/login -- but it times out whenever it tries to open subsequent URLs.
It seems that Selenium is listening for an event that just isn't triggered when only the URL hash changes.
I would imagine this happens any time you're using hashchange + Selenium...

In Selenium IDE simply use the 'storeEval' command, for example :
Command = storeEval
Target = window.location.hash='/search/events/birthdays/1'
storeEval runs the javascript snippet assigned to "target".
What you can then do, is have one test case that opens the start page using the open(url) command, and the rest of your cases changing the hash using the storeEval command.

Run this on console of developer tool -> window.location.hash='#abcde'. It should change hash for you in the browser tab.
Execute javascript through Selenium Webdriver and Java:
((JavascriptExecutor) driver).executeScript("window.location.hash='#abcde'");

A brief update: We gave up trying to use Selenium IDE to write our integration tests, and instead used the Selenium Python bindings for Selenium WebDriver.
With this approach, we can navigate to a URL and then use WebDriverWait to detect a particular change in the DOM, e.g.
driver = webdriver.Firefox()
driver.get("/#/login")
WebDriverWait(driver, 10).until(
lambda driver: driver.find_element_by_css_selector("form.login").is_displayed())

Related

Copy to clipboard in jupyter notebook

I'd like to implement a clipboard copy in a jupyter notebok.
The jupyter notebook is running remotely, thus I cannot use pandas.to_clipboard or pyperclip and I have to use javascript
This is what I came up with:
def js_code_copy(content)
return """
var body = document.getElementsByTagName('body')[0];
var tmp_textbox = document.createElement('input');
body.appendChild(tmp_textbox);
tmp_textbox.setAttribute('value', '{content}');
tmp_textbox.select();
document.execCommand('copy');
body.removeChild(tmp_textbox);
""".format(content=content.replace("'", '\\'+"'"))
Note that the code does what it's supposed to if I run it in my browser's console.
However, if I run it in jupyter with:
from IPython.display import display, Javascript
content = "boom"
display(Javascript(js_code_copy("Copy me to clipboard")))
Nothing works,
Any ideas ?
For security reasons, your browser disables the use of document.execCommand if the method wasn't called as a result of a user action, e.g clicking a button.
Since you're injecting and running Javascript on the page, this is not considered a user action.
You could try using selenium and phantomJS to run the code in a headless browser in the background.

clearing cache on chrome using web driver

We are testing web app using Jmeter selenium webdriver.
as HTTP manager doenst work we were trying to clear the cache using below Code. Due to some reason this is failling. We need clear cache mechanism to be implemented. Besides this we also tried incognito mode many other options as gooogle suggests without luck.
We are also trying to hit (Sendkeys) Enter after lauching browser as (chrome://settings/clearBrowserData) it on clear browsing window. Driver.close() will not help us as per the scenario needs.
Please throw some ideas / suggest how to execute Enter after browser launch.
Really appreciate your time and help.
var pkg=JavaImporter(org.openqa.selenium,org.openqa.selenium.support.ui) //import java selenium packages
var Thr=JavaImporter(java.lang.Thread) //import Thread sleep packages
var wait = new pkg.WebDriverWait(WDS.browser,30) //import WebDriverWait Package
WDS.browser.get('chrome://settings/clearBrowserData')
Thr.Thread.sleep(5000)
WDS.browser.switchTo().frame("settings")
var ChkBox = WDS.browser.findElement(pkg.By.xpath('//*[#id="delete-form-data-checkbox"]'))
ChkBox.click()
////*[#id="clear-browser-data-overlay"]/div[4]
//wait.until(pkg.ExpectedConditions.presenceOfElementLocated(pkg.By.xpath('//*[#id="clear-browser-data-commit"]')))
//wait.until(pkg.ExpectedConditions.presenceOfElementLocated(pkg.By.xpath('//*[#id="clear-browser-data-overlay"]/div[4]')))
var ClearCache = WDS.browser.findElement(pkg.By.xpath('//*[#id="clear-browser-data-commit"]'))
ClearCache.click()
wait.until(pkg.ExpectedConditions.presenceOfElementLocated(pkg.By.xpath('//*[#id="privacy-section"]/h3')))
The current chrome browser clear cache button is shadowed (its a ShadowDOM). We will not be able to interact with it directly. We will need to identify its JS path and perform the click using the executeScript function. No java packages need to be imported for the executeScript function.
Just append the below line for clearing the cache in your script.
WDS.browser.executeScript('return document.querySelector("body > settings-ui").shadowRoot.querySelector("#main").shadowRoot.querySelector("settings-basic-page").shadowRoot.querySelector("#advancedPage > settings-section:nth-child(1) > settings-privacy-page").shadowRoot.querySelector("settings-clear-browsing-data-dialog").shadowRoot.querySelector("#clearBrowsingDataConfirm").click();')
Happy testing using JMeter+WebDriver

How to test inline installation of Chrome extension in Protractor? [duplicate]

I am using selenium for some browser automation. I need to install an extension in the browser for my work. I am doing it as follows:
import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
executable_path = "/usr/bin/chromedriver"
options = Options()
options.add_extension('/home/TheRookie/Downloads/extensionSamples/abhcfceiempjmchhhdhbnkbimnfpckgl.crx')
browser = webdriver.Chrome(executable_path=executable_path, chrome_options=options)
The browser is starting fine but I am prompted with a pop-up to confirm that I want to add the extension as follows:
and after I get this pop-up, Python soon returns with the following exception:
selenium.common.exceptions.WebDriverException: Message: u'unknown
error: failed to wait for extension background page to load:
chrome-extension://abhcfceiempjmchhhdhbnkbimnfpckgl/toolbar.html\nfrom
unknown error: page could not be found:
chrome-extension://abhcfceiempjmchhhdhbnkbimnfpckgl/toolbar.html\n
(Driver info: chromedriver=2.12.301324
(de8ab311bc9374d0ade71f7c167bad61848c7c48),platform=Linux
3.13.0-39-generic x86_64)'
I tried handling the popup as a regular JavaScript alert using the following code:
alert = browser.switch_to_alert()
alert.accept()
However, this doesn't help. Could anyone please tell me how do I install this extension without the popup or a way to accept the popup? Any help would be greatly appreciated. Thanks!
Usually, you cannot test inline installation of a Chrome extension with just Selenium, because of that installation dialog. There are a few examples in the wild that show how to use external tools outside Selenium to solve this problem, but these are not very portable (i.e. platform-specific) and rely on a state of Chrome's UI, which is not guaranteed to be consistent.
But that does not mean that you cannot test inline installation. If you replace chrome.webstore.install with a substitute that behaves like the chrome.webstore.install API (but without the dialog), then the end-result is the same for all intents and purposes.
"Behaves like chrome.webstore.install" consists of two things:
Same behavior in error reporting and callback invocation.
An extension is installed.
I have just set up such an example on Github, which includes the source code of the helper extension/app and a few examples using Selenium (Python, Java). I suggest to read the README and the source code to get a better understanding of what happens: https://github.com/Rob--W/testing-chrome.webstore.install.
The sample does not require the tested extension to be available in the Chrome Web store. It does not even connect to the Chrome Web store. In particular, it does not check whether the site where the test runs is listed as a verified website, which is required for inline installation to work.
I had some really big code which I would have to re-write if I had to use Java. Luckily, python has a library for automating GUI events called ldtp. I used that to automate the clicking on the "Add" button. I did something on the following lines:
from ldtp import *
from threading import Thread
import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def thread_function():
for i in range(5):
if activatewindow('Confirm New Extension'):
generatekeyevent('<left><space>')
break
time.sleep(1)
def main():
executable_path = "/usr/bin/chromedriver"
options = Options()
options.add_extension('/home/TheRookie/Downloads/extensionSamples/abhcfceiempjmchhhdhbnkbimnfpckgl.crx')
thread.start()
browser = webdriver.Chrome(executable_path=executable_path, chrome_options=options)
Hope it helps somebody.

Use Selenium Webdriver to get periodically updated content

As an example, the chat site Omegle always displays on its homepage the current number of users online, which I am able to extract with this python script using the headless HTMLUnit Webdriver in Selenium:
from selenium import webdriver
driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.HTMLUNITWITHJS)
driver.get('http://www.omegle.com/')
element = driver.find_element_by_id("onlinecount")
print element.text.split()[0]
The output is like:
22,183
This number is dynamically generated and updated periodically by a script, and I want to read just this dynamically updated content at intervals without repeatedly loading the entire page with driver.get. What Selenium Webdriver method or functionality will let me do that?
This article seems like a relevant lead, though it led me nowehere.
This is untested, but I think the following might work:
from selenium import webdriver
from time import sleep
driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.HTMLUNITWITHJS)
driver.get('http://www.omegle.com/')
interval = 10 #or whatever interval you want
while True:
element = driver.find_element_by_id("onlinecount")
print element.text.split()[0]
sleep(interval)
I think if you find the element after it's been altered, it will give you the new value.

is it possible to develop a browser toolbar that accepts selenium automation

usually selenium does not identify elements on a browser toolbar. But this is for pre-build browser toolbars. Can a browser toolbar ( for FF, IE & Chrome ) be developed in such a way that selenium can be used to identify elements on the toolbar and then perform control actions on it , like clicking on a radio button on the toolbar.
Because Selenium can only control things that JavaScript can control, you need to find out whether JavaScript can control the toolbar. JavaScript has 3 main features. I controls the JavaScript processing, the DOM (document object model) and the BOM (browser object model). There might have been more control given to JavaScript when HTML 5 and CS3 came out, but this is my knowledge of it.
I think you may need to use a cross-browser extension to make your sidebar/toolbar. google-gears/silverlight/adobe-air/jnext. You might need to make the UI using the DOM. I'm not sure. You will need to research.. never done this before.
If the toolbar is part of the BOM (and/or DOM), then you can. Just create a custom command, called Selenium.prototype.doControlToolbar or something and put your JavaScript logic inside of that function (similar to what I have below). Good luck!
Option #1 - if using Selenium IDE:
Specify the user-extensions.js file under Selenium IDE > Options (menu) > Options (menu option) > General Tab, then browse to your file under "Selenium Core Extensions".
Option #2 - if using Selenium RC Server:
If you're not using the IDE and using Selenium RC server with a client driver (like JUnit for example), you must specify the path of the *.js file with the -userExtensions parameter when you start the Selenium RC Server on the command line. But you said you just wanted to use the IDE, so I'd ignore this. It takes quite a bit of other setup to use the Selenium RC server.
java -jar selenium-server.jar -userExtensions user-extensions.js
=======================
I made the following custom command (JavaScript function) in my custom user-extensions.js file.. I had to exit and restart the IDE before it found it. Type everything after the "do" in the "Command" field in the IDE to find the custom command. It looks like it also added a "customAlertAndWait" to the IDE as well.
Code in user-extensions.js file:
Selenium.prototype.doCustomAlert = function(sTarget, sValue) { alert('Target: ' + sTarget + ' ... Value: ' + sValue); };
Selenium IDE command details:
Command: customAlert
Target: custom alert target
Value: custom alert value

Categories

Resources