I have a HTML/Javascript file with google's web speech api and I'm doing testing using selenium, however everytime I enter the site the browser requests permission to use my microphone and I have to click on 'ALLOW'.
How do I make selenium click on ALLOW automatically ?
Wrestled with this quite a bit myself.
The easiest way to do this is to avoid getting the permission prompt is to add --use-fake-ui-for-media-stream to your browser switches.
Here's some shamelessly modified code from #ExperimentsWithCode's answer:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--use-fake-ui-for-media-stream")
driver = webdriver.Chrome(executable_path="path/to/chromedriver", chrome_options=chrome_options)
#ExperimentsWithCode
Thank you for your answer again, I have spent almost the whole day today trying to figure out how to do this and I've also tried your suggestion where you add that flag --disable-user-media-security to chrome, unfortunately it didn't work for me.
However I thought of a really simple solution:
To automatically click on Allow all I have to do is press TAB key three times and then press enter. And so I have written the program to do that automatically and it WORKS !!!
The first TAB pressed when my html page opens directs me to my input box, the second to the address bar and the third on the ALLOW button, then the Enter button is pressed.
The python program uses selenium as well as PyWin32 bindings.
Thank you for taking your time and trying to help me it is much appreciated.
So I just ran into another question asking about disabling a different prompt box. It seems there may be a way for you to accomplish your goal.
This page lists options for starting chrome. One of the options is
--disable-user-media-security
"Disables some security measures when accessing user media devices like webcams and microphones, especially on non-HTTPS pages"
So maybe this will work for you:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--disable-user-media-security=true")
driver = webdriver.Chrome(executable_path="path/to/chromedriver", chrome_options=chrome_options)
Beware of Mohana Latha's answer for JAVA!
The code is only pressing the buttons and NEVER releasing them. This will bring bunch of issues later on.
Use this instead:
// opening new window
Robot robot;
try {
robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.delay(100);
robot.keyPress(KeyEvent.VK_N);
robot.delay(100);
robot.keyRelease(KeyEvent.VK_N);
robot.delay(100);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.delay(100);
} catch (AWTException e) {
log.error("Failed to press buttons: " + e.getMessage());
}
Building on the answer from #Shady Programmer.
I tried to send Tab keys with selenium in order to focus on the popup, but as reported by others it didn't work in Linux. Therefore, instead of using selenium keys, I use xdotool command from python :
def send_key(winid, key):
xdotool_args = ['xdotool', 'windowactivate', '--sync', winid, 'key', key]
subprocess.check_output(xdotool_args)
which for Firefox, gives the following approximate sequence :
# Focusing on permissions popup icon
for i in range(6):
time.sleep(0.1)
send_key(win_info['winid'], 'Tab')
# Enter permissions popup
time.sleep(0.1)
send_key(win_info['winid'], 'space')
# Focus on "accept" button
for i in range(3):
time.sleep(0.1)
send_key(win_info['winid'], 'Tab')
# Press "accept"
send_key(win_info['winid'], 'a')
[Java]: Yes there is a simple technique to click on Allow button using Robot-java.awt
public void allowGEOLocationCapture(){
Robot robot = null;
try {
robot = new Robot();
robot.keyPress(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(600);
} catch (AWTException e) {
getLogger().info(e);
}
}
You can allow using add_experimental_option as shown below.
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option('prefs',{'profile.default_content_setting_values.notifications':1})
driver = webdriver.Chrome(chrome_options=chrome_options)
Do it
For android chrome it really work!
adb -s emulator-5554 push <YOU_COMPUTER_PATH_FOLDER>/com.android.chrome_preferences.xml /data/data/com.android.chrome/shared_prefs/com.android.chrome_preferences.xml
File config here https://yadi.sk/d/ubAxmWsN5RQ3HA
Chrome 80 x86
or you can save the settings file after ticking the box with your hands, in adb its "pull" - command
Related
I am implementing an appium test on remote android driver, with chrome browser for loading urls.
Some of the Urls are pdfs, and chrome asks to store those files. and appears that chrome doesnt have access to filesystem to store those files, which results in a dialog like below.
Please help me pass that dialog without any manual inputs.
Upon clicking continue, it will load actual permissions dialog from Android.
Here is my code initialize appium capabilities
DesiredCapabilities caps = DesiredCapabilities.android();
caps.setCapability("appiumVersion", "1.9.1");
caps.setCapability("deviceName","Samsung Galaxy S9 Plus HD GoogleAPI Emulator");
caps.setCapability("deviceOrientation", "portrait");
caps.setCapability("browserName", "Chrome");
caps.setCapability("platformVersion", "8.1");
caps.setCapability("platformName","Android");
caps.setCapability("autoAcceptAlerts", true);
caps.setCapability("autoGrantPermissions", true);
caps.setCapability("chromedriverArgs", "--allow-file-access-from-files");
caps.setCapability("maxDuration", 10000);
and this is the snippet I use to load a Url
driver.navigate().to("http://kmmc.in/wp-content/uploads/2014/01/lesson2.pdf");
autoGrantPermission also doesnt work in this case because chrome is already installed. Appium team has already rejected this issue -
https://github.com/appium/appium/issues/10008
Please help!
Indeed I had very hard time finding out the solution, but eventually I found a workaround.
The best workaround would have been reinstalling the chrome package. I tried that, but I could not start chrome after reinstalling it, as I had no access to shell, and chromedriver complained. So I left that track.
I tried getting hold of adb command or mobile:changePermissions but for that you need to use server flag --relaxed-security while starting the server, and saucelabs doesnt provide any handy interface to start the server with this flag.
The last resort, I found a solution here - https://stackoverflow.com/a/51241899/4675277 . But just that was not sufficient, because it helped me fix chrome alert, but later on it popped up with another alert with allow and deny, for which another solution in the same question helped me. So this is the code I eventually used -
driver.navigate().to("http://kmmc.in/wp-content/uploads/2014/01/lesson2.pdf");
String webContext = ((AndroidDriver)driver).getContext();
Set<String> contexts = ((AndroidDriver)driver).getContextHandles();
for (String context: contexts){
if (context.contains("NATIVE_APP")){
((AndroidDriver)driver).context(context);
break;
}
}
driver.findElement(By.id("android:id/button1")).click();
contexts = ((AndroidDriver)driver).getContextHandles();
for (String context: contexts){
if (context.contains("NATIVE_APP")){
((AndroidDriver)driver).context(context);
break;
}
}
driver.findElement(By.id("com.android.packageinstaller:id/permission_allow_button")).click();
((AndroidDriver)driver).context(webContext);
This helps allow all permissions required.
I need to load URL which has authentication pop up. I used http://username:password#exampl.com format to access the website via selenium webdriver on chrome browser.
But this support seems t be dropped in latest chrome browser, So loading the url is not successful. Browser keeps loading for a long time with no response from server.
Is there any alternate way to overcome authentication pop-up with selenium webdrier ? I know we can use sikui,autoit etc.But i need to run the same code on many platforms - Win/Mac/mobile/tablet.
So please let know how to overcome this.
I am using Selenium 3.4.0 and Chromedriver 2.31, and loading a URL with authentication credentials works fine for me.
As per I know chorme stop URL authentication from chrome 60.x version.
You can try below code or downgrade your chrome version
The Alert Method, authenticateUsing() lets you skip the Http Basic Authentication box.
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(username, password));
Hope it help you :)
After login in Chrome browser, I am getting a save password popup from the browser. I want to handle that popup and want to close that using Robot Framework
Browse popup window
Thanks
This question has been asked and answered before with a pure Python context. This answer continues on this SO post for a working Robot Example.
The popup you see is generated by Chrome itself. It's not an HTML alert. For this reason none of the Selenium2Library keywords will have any effect on it. Nor wil settings cookies or javascript.
These settings can be manually set using the chrome://settings link. Go to advanced settings and then scroll down to Passwords and Forms. Untick the second item and this will prevent the popup.
To do the same automatically in Robot Framework the WebDriver needs to be started with additional preferences:
Chrome With Preferences
${chrome_options} = Evaluate sys.modules['selenium.webdriver'].ChromeOptions() sys, selenium.webdriver
${prefs} Create Dictionary credentials_enable_service=${false}
Call Method ${chrome_options} add_experimental_option prefs ${prefs}
Call Method ${chrome_options} add_argument --disable-infobars
Create WebDriver Chrome chrome_options=${chrome_options}
Go To https://secure.url.com
This key things here are credentials_enable_service=${false} where it is important to use ${false} and not false, as the latter is interpreted as a string and then added to Chrome as "false" instead of the correct value false.
The second item is that preferences are not added as arguments but through assigning a dictionary to the prefs property of the ChromeOptions() object like so: add_experimental_option prefs ${prefs}
I do not think this is real to be honest (as it's property of the browser.) Are you having issues with that? The only thing you can dismiss is javascript alert and probably the best way to handle this is:
${alert} = Get Alert Message dismiss=${dismiss}
I have this in my test teardown with Run Keyword and Ignore Error, it makes me able to fetch optional js alert content and debug (also dismisses it do the rest of the suite can be executed.)
Three Ways To do do it.
1) Many a times, Once pop-up appear on screen and Disappear a cookie is set which you can view in developer console-> application. If you set this cookie with value using Add Cookie keyword. Pop- up wont appear.
2) if first doesn't work, then open developer tools and monitor the local store from developer tools -> application and close the pop-up. U will notice some variable with a value is stored in local storage. You can set that value using your script and u wont see the pop-up while executing variable.
3) If first and second doesn't work, the pop-up is most likely linked to a javascript variable. set java script variable using Execute Javascript Keyword and your problem must be solved.
Talk with your dev team, to see which way will work for you.
I am automating a test on aws.amazon.com to check whether the resources that i created using aws cli were successfully created or not using selenium webdriver. As the site falls out of my company network, to access the site i need to provide domain user/password in modal pop up that comes before hitting the url for the site.
i am not sure , but solution to this problem is to set profile/capability in the browser settings through the code. before hitting the url.
i have achieved that in firefox as follows
FirefoxProfile profile = new FirefoxProfile();
profile.addExtension(new File(Constants.FIREFOX_ADDON_PATH));
profile.setPreference("extensions.enabledAddons", "FireXPath%40pierre.tholence.com:0.9.7.1,proxyauth%40lammersoft.com:0.1.2,%7B972ce4c6-7e08-4474-a285-3208198ce6fd%7D:37.0.1");
profile.setPreference("extensions.proxyauth.authtoken","c3ViaGFtdDpub3YwNDIwMTQ=");
How to do the same in chrome and ie8 ?
i went through this but not able to comprehend anything.Also what does .xpi and .crx file has to do with all of this ?
This is pop up image for chrome
This is pop up image for IE8
The popup is a Windows Http Authentication popup and cannot be handled by using Selenium Webdriver. You will have to use either Robot Class or AutoIT to handle it.
1. Using Robot Class:
Alert authenticationWindow = driver.switchTo().alert();
// Type the username/email.
authenticationWindow.sendKeys("<username/email address>");
// Shift cursor focus to password input text field.
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_TAB);
// Type the password in password field. [ Selenium does not know at this point that the cursor focus is shifted, so calling Alert class instance sendKeys() will cause password to be typed in username field. So, we are copying the password first to windows clipboard and then pasting it directly into the password field using Robot class instance ]
StringSelection stringSelection = new StringSelection("<user password>");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection,null); robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
// Accept the authentication window.
robot.keyPress(KeyEvent.VK_ENTER);
2. Using AutoIT:
This link provides good information on how to use AutoIT alongwith Selenium: http://www.toolsqa.com/selenium-webdriver/autoit-selenium-webdriver/
Here is what you have to do:
Download/install AutoIT
You will be able to create .au3 scripts using AutoIT SciTe Editor
Compiling the .au3 script will give you a .exe file
Then you can invoke the .exe file from your Selenium script using
Runtime.getRuntime().exec("D:\AutoIt\AutoItTest.exe");
You can get the properties of a window using the AutoIT Window Info (x86) or (x64). Example, title / status bar of a window.
AutoIT also has Au3 Recorder so that you can record your actions that are related to the remote desktop.
Below is a sample script that automates Http authentication:
WinWaitActive("Web page title","","10")
If WinExists("Web page title") Then
Send("userid{TAB}")
Send("password{Enter}")
EndIf
3. Using AutoITx4Java:
Check this library AutoITx4Java - https://code.google.com/p/autoitx4java/
Download Jacob, AutoIT (refer the above link)
Add jacob.jar and autoitx4java.jar to your library path.
Place the jacob-1.15-M4-x64.dll file in your library path.
Sample Code
File file = new File("lib", "jacob-1.15-M4-x64.dll"); //path to the jacob dll
System.setProperty(LibraryLoader.JACOB_DLL_PATH, file.getAbsolutePath());
AutoItX x = new AutoItX();
String notepad = "Untitled - Notepad";
String testString = "this is a test.";
x.run("notepad.exe");
x.winActivate(notepad);
x.winWaitActive(notepad);
x.send(testString);
Assert.assertTrue(x.winExists(notepad, testString));
x.winClose(notepad, testString);
x.winWaitActive("Notepad");
x.send("{ALT}n");
Assert.assertFalse(x.winExists(notepad, testString));
I'm writing some selenium tests for a HTML5 player playing DRM content, the player works fine in Chrome when I test it manually, but nothing is loaded or played in the latest chrome driver if I run my test cases.
Is it because of the drm content isn't authorized to play in chrome driver or something else?
I have no issues running tests for other functions written in selenium.
Any ideas?
Chromedriver launches Chrome with --disable-component-update switch by default, which disables the NaCl (Native Client) support, which is in turn required to load DRM modules (e.g. Widevine Modular DRM).
To get around this, you need to tell the driver not to launch Chrome with this switch, by building the driver with excludeSwitches option, specifying disable-component-update parameter. For example (JS):
var webdriver = require('selenium-webdriver');
var chrome = require("selenium-webdriver/chrome");
var capabilities = new webdriver.Capabilities.chrome();
var chromeOptions = {
'args': ['--user-data-dir=C:/ChromeProfile'], // start with pre-configured Chrome profile
'excludeSwitches': ['disable-component-update'] // stop breaking Native Client support
};
capabilities.set('chromeOptions', chromeOptions);
var driver = new webdriver.Builder().
withCapabilities(capabilities).
build();
driver.get('http://...');
Or using Python bindings:
from selenium import webdriver
def buildDriver():
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['disable-component-update'])
options.add_argument('--user-data-dir=C:/Temp/ChromeProfile')
return webdriver.Chrome(chrome_options=options)
Hope that helps..
-- ab1
Issue 886: Enabled PNaCl Components in ChromeDriver - Enhancement
If you cannot get #Chainik's answer to work, try this out. It worked for me.
As per https://bugs.chromium.org/p/chromedriver/issues/detail?id=1140 you can work around this issue by doing a few things.
manually start chrome from terminal/command prompt with these command line arguments --
google-chrome --user-data-dir=/path/to/any/custom/directory/home/user/Desktop/Chromedir --profile-directory="Profile 1" --remote-debugging-port=7878
make sure "Profile 1" is already existing in the same --user-data-dir (make usre Profile 1 has necessary chrome://components/ to run Netflix when launched manually)
you can use any free port in place of 7878
verify that http://localhost:7878 is running and returns value.
now connect to the remote-debugging-port=7878 via chromedriver with code below
Verify chrome://components/
I put mine into a .bat file, but you could do the same for a bash script or whatever:
C:/Program Files (x86)/Google/Chrome/Application/chrome.exe --user-data=c:/temp/chromeprofile --profile-directory="Profile 1" --remote-debugging-port=7878
Then set the debugger address in your code to use the browser:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
cr_options = Options()
# This line is where the "magic" happens.
cr_options.add_experimental_option('debuggerAddress','127.0.0.1:7878')
browser = webdriver.Chrome(chrome_options=cr_options)
browser.get('https://www.google.com')
browser.get('chrome://components/')
I'm post a java version of Chainik's answer as a reference for those using Java, please let me know if there's anything wrong.
ChromeOptions options = new ChromeOptions();
List<String> list = new ArrayList<String>();
list.add("disable-component-update");
options.setExperimentalOption("excludeSwitches", list);
options.addArguments("user-data-dir=/Users/myname/Library/Application Support/Google/Chrome/Default");
java.lang.System.setProperty("webdriver.chrome.driver","/usr/bin/chromedriver");
Webdriver driver = new ChromeDriver(options);
Here is an article about chromedriver capabilities and options.
This is late but might help someone else. I was able to get around this and play videos by not using a headless browser.
In Python,
options = Options()
options.headless = False
webdriver.Chrome(executable_path='path/to/chromedriver', options=options)