To emulate the behavior of a mobile phone browser on WPM, we must modify the viewport using WebDriver and spoof the User-Agent header using the HttpClient as a proxy.
The base WebDriver object accesses the WebDriver Options through the manage
method. Nested in the options
is the WebDriver Window class which is accessible through the window
method.
var driver = openBrowser();
var currentDimension = driver.manage().window().getSize();
log(currentDimension.toString())
You can retrieve the current browser viewport using the getSize
method as shown above. In order to set the viewport using the setSize
metod, you must pass a Dimension object as an argument.
var newDimension = new org.openqa.selenium.Dimension(480, 800)
driver.manage().window().setSize(newDimension)
log(driver.manage().window().getSize().toString())
The Dimension class isn't mapped directly to an API on WPM's public endpoints, but is accessible using the full package name, as demonstrated in the snippet.
When using a real browser in WPM, the HttpClient can be used as a proxy to manipulate the HTTP request headers. This is accomplished using the removeHeader
method and addHeader
method.
var c = openHttpClient();
c.removeHeader('User-Agent');
c.addHeader('User-Agent', 'my-request-header/1.0');
Note: You want to remove the existing User-Agent before adding a new one, otherwise it will send a request with two User-Agent headers. Most servers will ignore the second header, in this scenario.
Upload MobileEmulator.js
to your data files in WPM.
- Log in
- Hover over "Scripting"
- Click "Data Files"
- Click "Upload A File"
- Select your file
Once the file is uploaded, it can be invoked from your scripts using the include
function. You must pass an instance of WebDriver and HttpClient as arguments.
include('MobileEmulator');
var driver = openBrowser();
var c = openHttpClient();
var emulator = new MobileEmulator(driver, c);
The module includes some templates of common phone dimensions and User-Agents. Selecting a template will automatically adjust the browser dimensions and User-Agent. You can view an array of valid template names using getEmulationTemplate
and choose a template with selectEmulationTemplate
.
log(JSON.stringify(emulator.getEmulationTemplates())); // write to log buffer
emulator.selectEmulationTemplate("iPhone-13");
The getInfo
method will return the current height, width and User-Agent of the browser.
log(JSON.stringify(emulator.getInfo()));
The setHeight
, setWidth
, and setUserAgent
methods can be used to manually specify said properties.
emulator.setWidth(600);
emulator.setHeight(800);
emulator.setUserAgent("my-request-header/1.0")
log(JSON.stringify(emulator.getInfo()))
This project is licensed under the terms of the MIT license. See LICENSE.md for more details.