I want to launch chrome browser with viewport size of some resolution , for example 800x600 , I tried following code
var width = 800;
var height = 600;
driver.manage().window().setSize(width, height);
Above code just resizing window to 800x600 , when I run window.screen.width in developer console it always return 1440
I even tried to add chrome option with --window-size=x,y option
var o = new chrome.Options();
o.addArguments("--window-size=640,480");
driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).setChromeOptions(o).build();
Above code still do the same ,just resizing the window.
Some one please tell me any chrome command line option to set default viewport like we do in chrome developer console (as shown below) , or please tell any option to do directly in selenium webdriverJS.
The code you are providing is working perfectly fine.
However, you are checking the resolution of the screen, not the size of the window! This is what window.screen.width and window.screen.height refer to. To retrieve the size of the window, use window.innerWidth (and innerHeight). The following works for me.
var webdriver = require('selenium-webdriver'),
driver = null;
function logWindowSize() {
driver.executeScript(function() {
return [window.innerWidth, window.innerHeight];
}).then(console.log);
}
// construct driver
driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.build();
driver.get('http://www.google.com');
// resize window
logWindowSize();
driver.manage().window().setSize(640, 480);
logWindowSize();
driver.quit();
This will log the following to my console.
[ 945, 1018 ]
[ 640, 375 ]
Note that the height of the window is different from what was set. This is because of the height of the tab bar and navigation bar. You can set the inner window size by first setting it to an arbitrary value, checking the difference and then setting it to what you want plus that difference. like so.
var webdriver = require('selenium-webdriver'),
driver = null,
sizeWidth = 640,
sizeHeight = 480;
// construct driver
driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.build();
driver.get('http://www.google.com');
// resize window
driver.manage().window().setSize(sizeWidth, sizeHeight);
driver.executeScript(function() {
return [window.innerWidth, window.innerHeight];
}).then(function(actualSize) {
driver.manage().window().setSize(
2 * sizeWidth - actualSize[0],
2 * sizeHeight - actualSize[1]
);
// the following will log the sizes we want
driver.executeScript(function() {
return [window.innerWidth, window.innerHeight];
}).then(console.log);
});
driver.quit();
The problem
It seems that you really want to influence what window.screen.width and window.screen.height return. This is normally not possible, except that these values change when using the device mode (and toolbar) in Chrome. So, let's trigger those, right?
// open inspector and responsive design mode
driver.actions()
.keyDown(Key.CONTROL)
.keyDown(Key.SHIFT)
.sendKeys('im')
.keyUp(Key.SHIFT)
.keyUp(Key.CONTROL)
.perform();
Unfortunately, this won't work in Chrome. To quote that answer:
The Chrome driver uses the Chrome remote debugging protocol to communicate with the browser. This is the same protocol that the developer console uses also. Unfortunately, Chrome is designed so that only one client can be attached using the protocol at a time, so that means either the developer tools, or the driver, but not both simultaneously. — JimEvans
Bummer. It looks like this can be made to work using Firefox, however. Unfortunately, it seems that performing actions is currently not possible using Selenium + geckodriver, at the moment. It is also not possible to open this mode using JavaScript. We can however send keys to an element.
A solution
The following works for me.
var webdriver = require('selenium-webdriver'),
firefox = require('selenium-webdriver/firefox'),
By = webdriver.By,
Key = webdriver.Key,
driver = null;
// construct driver
var profile = new firefox.Profile(),
devicePreset = [{
width: 640,
height: 480,
key: '640x480',
name: 'Mobile Device'
}];
profile.setPreference('devtools.responsiveUI.presets',
JSON.stringify(devicePreset));
var opts = new firefox.Options();
opts.setProfile(profile);
var builder = new webdriver.Builder().forBrowser('firefox');
builder.setFirefoxOptions(opts);
driver = builder.build();
driver.get('http://www.google.com');
// open responsive design mode
driver.findElement(By.css('input[name="q"]'))
.sendKeys(Key.chord(Key.CONTROL, Key.SHIFT, 'm'));
driver.get('https://www.iplocation.net/find-ip-address');
Note that I set a preference for Firefox that indicates the size to use in the responsive design mode. You can change this to whatever screen size you prefer.
Related
The title says it all: I am wondering whether it is possible to interact with the Firefox console upon starting Firefox in headless mode.
More generally, I'd settle for some way of accessing it programmatically, in scripts.
What I've tried:
So far I've been playing with the Javascript bindings to Selenium without success:
Starting Firefox with the -devtools option from Selenium does opn the dev tools, but I then cannot send key combinations that will switch me to the actual console, or in fact interact from my .js script with the open devtools window in any way.
Edit
In response to the first comment below: this answer does not seem to help. The console is not opened when I send CTRL+SHIFT+k to the body tag of google.com:
var webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
var firefox = require('selenium-webdriver/firefox');
var inpt = require('selenium-webdriver/lib/input');
var options = new firefox.Options();
var driver = new webdriver.Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build();
(async function(){
await driver.get('https://google.com');
var bdy = await driver.findElement(By.id('gsr'));
await bdy.sendKeys(inpt.Key.CONTROL + inpt.Key.SHIFT + 'k');
})();
This opens the page (google.com) and returns no errors, but there's no console anywhere.
For good measure: sending just inpt.Key.SHIFT + 'k' does enter a capital 'K' in the Google search field, so I know the keys are referenced correctly.
Also, sending just 'k' enters a small 'k' in the search field. It's only the three-key combo that does not work.
2nd edit:
I take it back: the newer answer does work, precisely as-is (I switched to Python from node).
The comment below by Karthik does resolve the matter, but I would like to summarize here and document working solutions that automate Firefox-Web-Console access.
The point of the answer I linked to above (in my 2nd edit) is that in order to have full access to the Firefox browser key controls one must
first switch Firefox context to chrome (from the default content context)
direct the automated browser driver to locate the element carrying id tabbrowser-tabs
send the key combo (in this case Ctrl+Shift+k) to that element.
Concrete working solutions:
Python
The script is
from selenium.webdriver import Firefox, DesiredCapabilities, FirefoxProfile
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.keys import Keys
import time
options = Options()
webdriver = Firefox(options=options)
webdriver.get("https://google.com")
try:
time.sleep(3)
with webdriver.context(webdriver.CONTEXT_CHROME):
console = webdriver.find_element(By.ID, "tabbrowser-tabs")
console.send_keys(Keys.LEFT_CONTROL + Keys.LEFT_SHIFT + 'k')
except:
pass
Run with python <path-to-script> it opens a Firefox window displaying google.com and the console at the bottom.
Javascript
Here the full script is
var webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
var firefox = require('selenium-webdriver/firefox');
var inpt = require('selenium-webdriver/lib/input');
var options = new firefox.Options();
var driver = new webdriver.Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build();
(async function(){
await driver.get('https://google.com');
await driver.setContext("chrome");
var tabs = await driver.findElement(By.id('tabbrowser-tabs'));
await tabs.sendKeys(inpt.Key.CONTROL + inpt.Key.SHIFT + 'k');
})();
Run with node <path-to-script> it achieves the same effect as above: a Firefox window open on google.com, with the console open at the bottom.
During the test when the application start, after a while a new browser opens.
How do I set the new browser instance as full screen not as maximize?
For the Google Chrome browser, you can add --start-fullscreen argument to start in fullscreen mode, like if the user had pressed F11 right after startup. Add it to the chromeOptions object in the protractor.conf.js file.
chromeOptions: {
args: ['--start-fullscreen']
}
Using Javascript executor, you can do something like
max_width, max_height = driver.execute_script("return [window.screen.availWidth, window.screen.availHeight];")
browser.driver.manage().window().setSize(max_width, max_height);
Before getting the available width and available height and then the window size as suggested by #demouser123
You need to switch the handle to new browser instance, otherwise browser.driver will keep pointing to first browse.
I am using java + selenium webdriver for webautomaiton.
For safari browser 10.1 version, I need the browser to be full screen before test started.However
driver.manage().window().maximize();
does not work
I tried few options but no luck.
1.
seems no option available for doing something like which would write in the plist file of /Library/Preferences folder of mac
defaults write com.apple.Safari
2
WebElement element = Wait.wait.until(visibilityOfElementLocated(By.cssSelector(".logo-large")));
element.sendKeys(Keys.CONTROL , Keys.COMMAND , "f");
element.sendKeys(Keys.CONTROL , Keys.COMMAND , "F");
Actions action = new Actions(driver);
action.keyDown(Keys.CONTROL).keyDown(Keys.COMMAND).sendKeys("F").perform();
action.keyDown(Keys.CONTROL).keyDown(Keys.COMMAND).sendKeys("f").perform();
Is there anyway I can do it using send keys, or write in the plist file or through javascript.
Try below :-
public static void maximizeScreen(WebDriver driver) {
java.awt.Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Point position = new Point(0, 0);
driver.manage().window().setPosition(position);
Dimension maximizedScreenSize =
new Dimension((int) screenSize.getWidth(), (int) screenSize.getHeight());
driver.manage().window().setSize(maximizedScreenSize);
}
Hore it will help you
Take a look here (Native Fullscreen JavaScript API): http://johndyer.name/native-fullscreen-javascript-api-plus-jquery-plugin/
Sample:http://johndyer.name/lab/fullscreenapi/
You have to update the safari browser, update the browser with Safari 11+ version
then you are able to maximize it using this code:
driver.manage().window().maximize();
I am writing a Firefox add-on, and I am using the high-level Firefox Add-on SDK API.
My add-on opens a new window, and opens several tabs in that window.
How can I get this new window to open in the background? I do not want its opening to disrupt the user's focus on the active window.
When opening a tab, there is an inBackground option that can be used for this.
I have searched the windows module documentation high and low, but I cannot find a similar option for when creating new windows!
How do I open this new window in the background?
If Mozilla forbids me from doing so, is there a way I can very quickly push the new window to the background just after it opens, so that it is minimally disruptive?
Not disallowed. Perfectly fine. Do it with a features option of alwaysLowered I think.
Full list of features found here: https://developer.mozilla.org/en-US/docs/Web/API/window.open#Position_and_size_features
var sa = Cc["#mozilla.org/supports-array;1"].createInstance(Ci.nsISupportsArray);
var wuri = Cc["#mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
wuri.data = 'about:blank';
sa.AppendElement(wuri);
let features = "chrome,dialog=no,alwaysLowered";
var wantTabs = false;
if (wantTabs) {
features += ',all';
}
/*var sDOMWin = aTab.ownerGlobal; //source DOMWindow*/
if (PrivateBrowsingUtils.permanentPrivateBrowsing/* || PrivateBrowsingUtils.isWindowPrivate(sDOMWin)*/) {
features += ",private";
} else {
features += ",non-private";
}
var XULWindow = Services.ww.openWindow(null, 'chrome://browser/content/browser.xul', null, features, sa);
You can tag this code onto the end to do something after the XULWindow loads:
XULWindow.addEventListener('load', function() {
//can lower or raise the window z-index here
var DOMWindow = XULWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
DOMWindow.gBrowser.selectedTab.linkedBrowser.webNavigation.stop(Ci.nsIWebNavigation.STOP_ALL);
}, false);
With the below code block it opens a chrome browser fine it just won't full screen the browser using F11. i used to use C# and selenium and that worked fine using this method on chrome and different browsers. It finds the element 'body' but then does not send the key press. Am I doing something wrong here that i should be requiring some other library?
the documentation for webdriverjs is pathetic and there is very few examples, I am seriously considering dumping it for something else possibly python.
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
driver.get('https://www.google.co.uk/');
driver.wait(function () {
return driver.getTitle().then(function (title) {
return title === 'Google';
});
}, 1000);
driver.findElement(webdriver.By.xpath('/html/body')).sendKeys("F11");
why are we doing this. we are developing a website that will change depending on size 800x600 + with and without the toolbar depending on how the screen is used different items will be displayed. i can maximise the window using,
driver.manage().window().maximize();
This however still leaves the toolbar present and doesn't act as if the user has pressed the F11 key.
it tooks some time to find it but you should have all the Keys in webdriver.Key
driver.findElement(webdriver.By.xpath('/html/body')).sendKeys(webdriver.Key.F11);
Hope it helps!
A co-worker has just discovered that it works well in C# with:
Driver.Instance.Manage().Window.FullScreen();
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
ActionChains(driver).send_keys(Keys.F11).perform()
I use a similar command to toggle JS via Firefox's NoScript add-on
edit: I just tested, and it works!
This should work for you:
driver.findElement(webdriver.By.xpath('/html/body')).sendKeys(Keys.F11);
You can maximise the window using:
driver.manage().window().maximize();
For me the one emulating correctly the F11 on startup is:
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-fullscreen");
WebDriver driver = new ChromeDriver(options);
Or if the kiosk mode is preferred:
ChromeOptions options = new ChromeOptions();
options.addArguments("--kiosk");
WebDriver driver = new ChromeDriver(options);