chore: move emulateTimeZone and setGeolocation to Overrides (#92)

This commit is contained in:
Pavel Feldman 2019-11-26 15:13:49 -08:00 committed by Dmitry Gozman
parent c7a07ea2a8
commit cc41377fe2
6 changed files with 39 additions and 40 deletions

View file

@ -60,8 +60,9 @@
* [browserContext.setCookies(cookies)](#browsercontextsetcookiescookies) * [browserContext.setCookies(cookies)](#browsercontextsetcookiescookies)
* [browserContext.targets()](#browsercontexttargets) * [browserContext.targets()](#browsercontexttargets)
* [browserContext.waitForTarget(predicate[, options])](#browsercontextwaitfortargetpredicate-options) * [browserContext.waitForTarget(predicate[, options])](#browsercontextwaitfortargetpredicate-options)
- [class: Geolocation](#class-geolocation) - [class: Overrides](#class-overrides)
* [geolocation.set(options)](#geolocationsetoptions) * [overrides.setGeolocation(options)](#overridessetgeolocationoptions)
* [overrides.setTimezone(timezoneId)](#overridessettimezonetimezoneid)
- [class: Permissions](#class-permissions) - [class: Permissions](#class-permissions)
* [permissions.clearOverrides()](#permissionsclearoverrides) * [permissions.clearOverrides()](#permissionsclearoverrides)
* [permissions.override(origin, permissions)](#permissionsoverrideorigin-permissions) * [permissions.override(origin, permissions)](#permissionsoverrideorigin-permissions)
@ -97,7 +98,6 @@
* [page.dblclick(selector[, options])](#pagedblclickselector-options) * [page.dblclick(selector[, options])](#pagedblclickselector-options)
* [page.emulate(options)](#pageemulateoptions) * [page.emulate(options)](#pageemulateoptions)
* [page.emulateMedia(options)](#pageemulatemediaoptions) * [page.emulateMedia(options)](#pageemulatemediaoptions)
* [page.emulateTimezone(timezoneId)](#pageemulatetimezonetimezoneid)
* [page.evaluate(pageFunction[, ...args])](#pageevaluatepagefunction-args) * [page.evaluate(pageFunction[, ...args])](#pageevaluatepagefunction-args)
* [page.evaluateHandle(pageFunction[, ...args])](#pageevaluatehandlepagefunction-args) * [page.evaluateHandle(pageFunction[, ...args])](#pageevaluatehandlepagefunction-args)
* [page.evaluateOnNewDocument(pageFunction[, ...args])](#pageevaluateonnewdocumentpagefunction-args) * [page.evaluateOnNewDocument(pageFunction[, ...args])](#pageevaluateonnewdocumentpagefunction-args)
@ -105,7 +105,6 @@
* [page.fill(selector, value)](#pagefillselector-value) * [page.fill(selector, value)](#pagefillselector-value)
* [page.focus(selector)](#pagefocusselector) * [page.focus(selector)](#pagefocusselector)
* [page.frames()](#pageframes) * [page.frames()](#pageframes)
* [page.geolocation](#pagegeolocation)
* [page.goBack([options])](#pagegobackoptions) * [page.goBack([options])](#pagegobackoptions)
* [page.goForward([options])](#pagegoforwardoptions) * [page.goForward([options])](#pagegoforwardoptions)
* [page.goto(url[, options])](#pagegotourl-options) * [page.goto(url[, options])](#pagegotourl-options)
@ -115,6 +114,7 @@
* [page.keyboard](#pagekeyboard) * [page.keyboard](#pagekeyboard)
* [page.mainFrame()](#pagemainframe) * [page.mainFrame()](#pagemainframe)
* [page.mouse](#pagemouse) * [page.mouse](#pagemouse)
* [page.overrides](#pageoverrides)
* [page.pdf](#pagepdf) * [page.pdf](#pagepdf)
* [page.reload([options])](#pagereloadoptions) * [page.reload([options])](#pagereloadoptions)
* [page.screenshot([options])](#pagescreenshotoptions) * [page.screenshot([options])](#pagescreenshotoptions)
@ -844,9 +844,9 @@ await page.evaluate(() => window.open('https://www.example.com/'));
const newWindowTarget = await browserContext.waitForTarget(target => target.url() === 'https://www.example.com/'); const newWindowTarget = await browserContext.waitForTarget(target => target.url() === 'https://www.example.com/');
``` ```
### class: Geolocation ### class: Overrides
#### geolocation.set(options) #### overrides.setGeolocation(options)
- `options` <[Object]> - `options` <[Object]>
- `latitude` <[number]> Latitude between -90 and 90. - `latitude` <[number]> Latitude between -90 and 90.
- `longitude` <[number]> Longitude between -180 and 180. - `longitude` <[number]> Longitude between -180 and 180.
@ -856,11 +856,14 @@ const newWindowTarget = await browserContext.waitForTarget(target => target.url(
Sets the page's geolocation. Sets the page's geolocation.
```js ```js
await page.geolocation.set({latitude: 59.95, longitude: 30.31667}); await page.overrides.setGeolocation({latitude: 59.95, longitude: 30.31667});
``` ```
> **NOTE** Consider using [browserContext.permissions.override](#permissionsoverrideorigin-permissions) to grant permissions for the page to read its geolocation. > **NOTE** Consider using [browserContext.permissions.override](#permissionsoverrideorigin-permissions) to grant permissions for the page to read its geolocation.
#### overrides.setTimezone(timezoneId)
- `timezoneId` <?[string]> Changes the timezone of the page. See [ICUs `metaZones.txt`](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1) for a list of supported timezone IDs. Passing `null` disables timezone emulation.
- returns: <[Promise]>
### class: Permissions ### class: Permissions
@ -1269,10 +1272,6 @@ await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').ma
// → false // → false
``` ```
#### page.emulateTimezone(timezoneId)
- `timezoneId` <?[string]> Changes the timezone of the page. See [ICUs `metaZones.txt`](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1) for a list of supported timezone IDs. Passing `null` disables timezone emulation.
- returns: <[Promise]>
#### page.evaluate(pageFunction[, ...args]) #### page.evaluate(pageFunction[, ...args])
- `pageFunction` <[function]|[string]> Function to be evaluated in the page context - `pageFunction` <[function]|[string]> Function to be evaluated in the page context
- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction` - `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`
@ -1443,9 +1442,6 @@ Shortcut for [page.mainFrame().focus(selector)](#framefocusselector).
#### page.frames() #### page.frames()
- returns: <[Array]<[Frame]>> An array of all frames attached to the page. - returns: <[Array]<[Frame]>> An array of all frames attached to the page.
#### page.geolocation
- returns: <[Geolocation]>
#### page.goBack([options]) #### page.goBack([options])
- `options` <[Object]> Navigation parameters which might have the following properties: - `options` <[Object]> Navigation parameters which might have the following properties:
- `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods. - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
@ -1535,6 +1531,9 @@ Page is guaranteed to have a main frame which persists during navigations.
- returns: <[Mouse]> - returns: <[Mouse]>
#### page.overrides
- returns: <[Overrides]>
#### page.pdf #### page.pdf
- returns: <[PDF]> - returns: <[PDF]>

View file

@ -30,7 +30,7 @@ import { EmulationManager } from './EmulationManager';
import { Events } from './events'; import { Events } from './events';
import { Accessibility } from './features/accessibility'; import { Accessibility } from './features/accessibility';
import { Coverage } from './features/coverage'; import { Coverage } from './features/coverage';
import { Geolocation } from './features/geolocation'; import { Overrides } from './features/overrides';
import { Interception } from './features/interception'; import { Interception } from './features/interception';
import { PDF } from './features/pdf'; import { PDF } from './features/pdf';
import { Workers } from './features/workers'; import { Workers } from './features/workers';
@ -68,7 +68,7 @@ export class Page extends EventEmitter {
private _emulationManager: EmulationManager; private _emulationManager: EmulationManager;
readonly accessibility: Accessibility; readonly accessibility: Accessibility;
readonly coverage: Coverage; readonly coverage: Coverage;
readonly geolocation: Geolocation; readonly overrides: Overrides;
readonly interception: Interception; readonly interception: Interception;
readonly pdf: PDF; readonly pdf: PDF;
readonly workers: Workers; readonly workers: Workers;
@ -102,7 +102,7 @@ export class Page extends EventEmitter {
this.coverage = new Coverage(client); this.coverage = new Coverage(client);
this.pdf = new PDF(client); this.pdf = new PDF(client);
this.workers = new Workers(client, this._addConsoleMessage.bind(this), this._handleException.bind(this)); this.workers = new Workers(client, this._addConsoleMessage.bind(this), this._handleException.bind(this));
this.geolocation = new Geolocation(client); this.overrides = new Overrides(client);
this.interception = new Interception(this._frameManager.networkManager()); this.interception = new Interception(this._frameManager.networkManager());
this._screenshotTaskQueue = screenshotTaskQueue; this._screenshotTaskQueue = screenshotTaskQueue;
@ -501,16 +501,6 @@ export class Page extends EventEmitter {
this._emulatedMediaType = options.type; this._emulatedMediaType = options.type;
} }
async emulateTimezone(timezoneId: string | null) {
try {
await this._client.send('Emulation.setTimezoneOverride', {timezoneId: timezoneId || ''});
} catch (exception) {
if (exception.message.includes('Invalid timezone'))
throw new Error(`Invalid timezone ID: ${timezoneId}`);
throw exception;
}
}
async setViewport(viewport: Viewport) { async setViewport(viewport: Viewport) {
const needsReload = await this._emulationManager.emulateViewport(viewport); const needsReload = await this._emulationManager.emulateViewport(viewport);
this._viewport = viewport; this._viewport = viewport;

View file

@ -11,7 +11,7 @@ export { Dialog } from './Dialog';
export { ExecutionContext } from './ExecutionContext'; export { ExecutionContext } from './ExecutionContext';
export { Accessibility } from './features/accessibility'; export { Accessibility } from './features/accessibility';
export { Coverage } from './features/coverage'; export { Coverage } from './features/coverage';
export { Geolocation } from './features/geolocation'; export { Overrides } from './features/overrides';
export { Interception } from './features/interception'; export { Interception } from './features/interception';
export { PDF } from './features/pdf'; export { PDF } from './features/pdf';
export { Permissions } from './features/permissions'; export { Permissions } from './features/permissions';

View file

@ -25,11 +25,11 @@ module.exports.addTests = function ({ testRunner, expect }) {
// FIXME: not supported in WebKit (as well as Emulation domain in general). // FIXME: not supported in WebKit (as well as Emulation domain in general).
// It was removed from WebKit in https://webkit.org/b/126630 // It was removed from WebKit in https://webkit.org/b/126630
describe('Geolocation.set', function() { describe('Overrides.setGeolocation', function() {
it('should work', async({page, server, context}) => { it('should work', async({page, server, context}) => {
await context.permissions.override(server.PREFIX, ['geolocation']); await context.permissions.override(server.PREFIX, ['geolocation']);
await page.goto(server.EMPTY_PAGE); await page.goto(server.EMPTY_PAGE);
await page.geolocation.set({longitude: 10, latitude: 10}); await page.overrides.setGeolocation({longitude: 10, latitude: 10});
const geolocation = await page.evaluate(() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => { const geolocation = await page.evaluate(() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {
resolve({latitude: position.coords.latitude, longitude: position.coords.longitude}); resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
}))); })));
@ -41,7 +41,7 @@ module.exports.addTests = function ({ testRunner, expect }) {
it('should throw when invalid longitude', async({page, server, context}) => { it('should throw when invalid longitude', async({page, server, context}) => {
let error = null; let error = null;
try { try {
await page.geolocation.set({longitude: 200, latitude: 10}); await page.overrides.setGeolocation({longitude: 200, latitude: 10});
} catch (e) { } catch (e) {
error = e; error = e;
} }

View file

@ -17,14 +17,14 @@
import { CDPSession } from '../Connection'; import { CDPSession } from '../Connection';
export class Geolocation { export class Overrides {
private _client: CDPSession; private _client: CDPSession;
constructor(client: CDPSession) { constructor(client: CDPSession) {
this._client = client; this._client = client;
} }
async set(options: { longitude: number; latitude: number; accuracy: (number | undefined); }) { async setGeolocation(options: { longitude: number; latitude: number; accuracy: (number | undefined); }) {
const { longitude, latitude, accuracy = 0} = options; const { longitude, latitude, accuracy = 0} = options;
if (longitude < -180 || longitude > 180) if (longitude < -180 || longitude > 180)
throw new Error(`Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`); throw new Error(`Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`);
@ -34,4 +34,14 @@ export class Geolocation {
throw new Error(`Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`); throw new Error(`Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`);
await this._client.send('Emulation.setGeolocationOverride', {longitude, latitude, accuracy}); await this._client.send('Emulation.setGeolocationOverride', {longitude, latitude, accuracy});
} }
async setTimezone(timezoneId: string | null) {
try {
await this._client.send('Emulation.setTimezoneOverride', {timezoneId: timezoneId || ''});
} catch (exception) {
if (exception.message.includes('Invalid timezone'))
throw new Error(`Invalid timezone ID: ${timezoneId}`);
throw exception;
}
}
} }

View file

@ -139,29 +139,29 @@ module.exports.addTests = function({testRunner, expect, playwright, FFOX, CHROME
}); });
}); });
describe.skip(FFOX || WEBKIT)('Page.emulateTimezone', function() { describe.skip(FFOX || WEBKIT)('Overrides.setTimezone', function() {
it('should work', async({page, server}) => { it('should work', async({page, server}) => {
page.evaluate(() => { page.evaluate(() => {
globalThis.date = new Date(1479579154987); globalThis.date = new Date(1479579154987);
}); });
await page.emulateTimezone('America/Jamaica'); await page.overrides.setTimezone('America/Jamaica');
expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 13:12:34 GMT-0500 (Eastern Standard Time)'); expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 13:12:34 GMT-0500 (Eastern Standard Time)');
await page.emulateTimezone('Pacific/Honolulu'); await page.overrides.setTimezone('Pacific/Honolulu');
expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 08:12:34 GMT-1000 (Hawaii-Aleutian Standard Time)'); expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 08:12:34 GMT-1000 (Hawaii-Aleutian Standard Time)');
await page.emulateTimezone('America/Buenos_Aires'); await page.overrides.setTimezone('America/Buenos_Aires');
expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 15:12:34 GMT-0300 (Argentina Standard Time)'); expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 15:12:34 GMT-0300 (Argentina Standard Time)');
await page.emulateTimezone('Europe/Berlin'); await page.overrides.setTimezone('Europe/Berlin');
expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 19:12:34 GMT+0100 (Central European Standard Time)'); expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 19:12:34 GMT+0100 (Central European Standard Time)');
}); });
it('should throw for invalid timezone IDs', async({page, server}) => { it('should throw for invalid timezone IDs', async({page, server}) => {
let error = null; let error = null;
await page.emulateTimezone('Foo/Bar').catch(e => error = e); await page.overrides.setTimezone('Foo/Bar').catch(e => error = e);
expect(error.message).toBe('Invalid timezone ID: Foo/Bar'); expect(error.message).toBe('Invalid timezone ID: Foo/Bar');
await page.emulateTimezone('Baz/Qux').catch(e => error = e); await page.overrides.setTimezone('Baz/Qux').catch(e => error = e);
expect(error.message).toBe('Invalid timezone ID: Baz/Qux'); expect(error.message).toBe('Invalid timezone ID: Baz/Qux');
}); });
}); });