display_override - Web app manifests

display\_override
=================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

|  |  |
| --- | --- |
| Type | `Array` |

The `display` member is used to determine the developer's preferred display mode for a website. It follows a process where the browser falls back to the next display mode if the requested one is not supported. In some advanced use cases, this fallback process might not be enough.

The `display_override` member solves this by letting the developer provide a sequence of display modes that the browser will consider before using the `display` member. Its value is an array of display modes that are considered in-order, and the first supported display mode is applied.

Values
------

Display override objects are display-mode strings, the possible values are:

| Display Mode | Description |
| --- | --- |
| `fullscreen` |
 All of the available display area is used and no user agent
 chrome is shown.
  |
| `standalone` |
 The application will look and feel like a standalone application. This
 can include the application having a different window, its own icon in
 the application launcher, etc. In this mode, the user agent will exclude
 UI elements for controlling navigation, but can include other UI
 elements such as a status bar.
  |
| `minimal-ui` |
 The application will look and feel like a standalone application, but
 will have a minimal set of UI elements for controlling navigation. The
 elements will vary by browser.
  |
| `browser` |
 The application opens in a conventional browser tab or new window,
 depending on the browser and platform. This is the default.
  |
| `window-controls-overlay` |
 This display mode only applies when the application is in a separate PWA
 window and on a desktop operating system. The application will opt-in to
 the Window Controls Overlay feature, where the full window surface area
 will be available for the app's web content and the window control buttons
 (maximize, minimize, close, and other PWA-specific buttons) will appear
 as an overlay above the web content.
  |

Example
-------

In the example below, the browser will consider the following display-mode fallback chain in this order: `fullscreen` → `minimal-ui` → `standalone`.

```json
{
  "display\_override": ["fullscreen", "minimal-ui"],
  "display": "standalone"
}
```

Specifications
--------------

| Specification |
| --- |
| Manifest Incubations # display\_override-member |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Preparing for the display modes of tomorrow
* Customize the window controls overlay of your PWA's title bar


screenshots - Web app manifests

screenshots
===========

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

|  |  |
| --- | --- |
| Type | `Array` |

The `screenshots` member defines an array of screenshots intended to showcase the application. These images are intended to be used by progressive web app stores.

Properties
----------

The `screenshots` member is an array of objects each representing a screenshot. Each screenshot object may contain the following properties:

`form_factor`

String that represents a class of devices. This should be used only when the screenshot is only applicable for a particular form factor.

This property may take one of the following values:

* `"narrow"`: the screenshot is applicable only to narrow screens.
* `"wide"`: the screenshot is applicable only to wide screens.

`label`

String that represents the accessible name of the screenshot object. This member can serve as alternative text for the screenshot.

`platform`

String that represents the platform to which the screenshot applies. This should be used when a screenshot is only applicable to a specific device or distribution platform. User agents should not show screenshots that contain a `platform` value that differs from the current platform (for example, Google Play should not show screenshots whose `platform` is `"ios"`).

This property may take one of the following values:

* Device platform identifiers:
    + `"android"`
    + `"chromeos"`
    + `"ipados"`
    + `"ios"`
    + `"kaios"`
    + `"macos"`
    + `"windows"`
    + `"xbox"`
* Distribution platform identifiers:
    + `"chrome_web_store"`
    + `"itunes"`
    + `"microsoft-inbox"`
    + `"microsoft-store"`
    + `"play"`

`sizes`

String that describes the size of the image, or multiple sizes for image formats such as ICO that can contain multiple images. This property is equivalent to, and specified in the same way as, the `sizes` attribute of the `<link>` element.

`src`

String representing a URL from which the user agent can fetch the image data.

`type`

String representing the MIME type for the image.

Examples
--------

```json
"screenshots" : [
  {
    "src": "screenshot1.webp",
    "sizes": "1280x720",
    "type": "image/webp",
    "form\_factor": "wide",
    "label": "Homescreen of Awesome App"
  },
  {
    "src": "screenshot2.webp",
    "sizes": "1280x720",
    "type": "image/webp",
    "form\_factor": "wide",
    "label": "List of Awesome Resources available in Awesome App"
  }
]
```

Specifications
--------------

| Specification |
| --- |
| Web App Manifest - Application Information # screenshots-member |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


launch_handler - Web app manifests

launch\_handler
===============

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

|  |  |
| --- | --- |
| Type | `Object` |

The `launch_handler` member defines values that control the launch of a web application. Currently it can only contain a single value, `client_mode`, which specifies the context in which the app should be loaded when launched. For example, in an existing web app client containing an instance of the app, or in a new web app client. This leaves scope for more `launch_handler` values to be defined in the future.

launch\_handler item values
---------------------------

`launch_handler` objects may contain the following values:

| Member | Description |
| --- | --- |
| `client_mode` | A string, or comma-separated array of strings, which specifies the context in which the app should be loaded when launched. If an array of strings is provided, the first valid value is used. Possible values are:

`auto`
The user agent decides what context makes sense for the platform to load the app in. For example, `navigate-existing` might make more sense on mobile, where single app instances are commonplace, whereas `navigate-new` might make more sense in a desktop context. This is the default value used if all the provided values are invalid.
`focus-existing`
If the app is already loaded in a web app client, it is brought into focus but not navigated to the launch target URL. The target URL is made available via `Window.launchQueue` to allow custom launch navigation handling to be implemented. If the app is not already loaded in a web app client, `navigate-new` behavior is used instead.
`navigate-existing`
If the app is already loaded in a web app client, it is brought into focus and navigated to the specified launch target URL. The target URL is made available via `Window.launchQueue` to allow additional custom launch navigation handling to be implemented. If the app is not already loaded in a web app client, `navigate-new` behavior is used instead.
`navigate-new`
The app is loaded inside a new web app client. The target URL is made available via `Window.launchQueue` to allow additional custom launch navigation handling to be implemented.
 |

Examples
--------

```json
"launch\_handler": {
    "client\_mode": "focus-existing"
}

"launch\_handler": {
    "client\_mode": ["focus-existing", "auto"]
}
```

Specifications
--------------

| Specification |
| --- |
| Web App Launch Handler API # launch\_handler-member |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Launch Handler API: Control how your app is launched
* `Window.launchQueue`
* Musicr 2.0 demo app


related_applications - Web app manifests

related\_applications
=====================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

|  |  |
| --- | --- |
| Type | `Array` |

The `related_applications` field is an array of objects specifying native applications that are installable by, or accessible to, the underlying platform — for example, a native Android application obtainable through the Google Play Store. Such applications are intended to be alternatives to the manifest's website that provides similar/equivalent functionality — like the native app equivalent.

**Note:** Developer can specify that the native applications are preferred over the web application by setting `prefer_related_applications` to `true`.

Examples
--------

```json
"related\_applications": [
  {
    "platform": "play",
    "url": "https://play.google.com/store/apps/details?id=com.example.app1",
    "id": "com.example.app1"
  }, {
    "platform": "itunes",
    "url": "https://itunes.apple.com/app/example-app1/id123456789"
  }, {
    "platform": "windows",
    "url": "https://apps.microsoft.com/store/detail/example-app1/id123456789"
  }
]
```

Related application properties
------------------------------

Application objects may contain the following properties:

| Member | Description |
| --- | --- |
| `platform` | The platform on which the application can be found. List of available values |
| `url` | The URL at which the application can be found. |
| `id` | The ID used to represent the application on the specified platform. |

Specifications
--------------

| Specification |
| --- |
| Web Application Manifest # related\_applications-member |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


background_color - Web app manifests

background\_color
=================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

|  |  |
| --- | --- |
| Type | `String` |

The `background_color` member defines a placeholder background color for the application page to display before its stylesheet is loaded. This value is used by the user agent to draw the background color of a shortcut when the manifest is available before the stylesheet has loaded.

Therefore `background_color` should match the `background-color` CSS property in the site's stylesheet for a smooth transition between launching the web application and loading the site's content.

**Note:** The `background_color` member is only meant to improve the user experience while the main stylesheet is loading from the network or the storage media; it is not used by the user agent as the `background-color` CSS property when the progressive web app stylesheet is available.

Examples
--------

```json
"background\_color": "red"
```

Specifications
--------------

| Specification |
| --- |
| Web Application Manifest # background\_color-member |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


description - Web app manifests

description
===========

|  |  |
| --- | --- |
| Type | `String` |

The `description` member is a string in which developers can explain what the application does. `description` is directionality-capable, which means it can be displayed left to right or right to left based on the values of the `dir` and `lang` manifest members.

Examples
--------

Simple `description` in left-to-right language:

```json
"description": "Awesome application that will help you achieve your dreams."
```

`description` in Arabic, which will be displayed right-to-left:

```json
"dir": "rtl",
"lang": "ar",
"description": ".تطبيق رائع سيساعدك على تحقيق أحلامك"
```

Specifications
--------------

| Specification |
| --- |
| Web App Manifest - Application Information # description-member |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


name - Web app manifests

name
====

|  |  |
| --- | --- |
| Type | `String` |

The `name` member is a string that represents the name of the web application as it is usually displayed to the user (e.g., amongst a list of other applications, or as a label for an icon). `name` is directionality-capable, which means it can be displayed left-to-right or right-to-left based on the values of the `dir` and `lang` manifest members.

Examples
--------

Simple `name` in left-to-right language:

```json
"name": "Awesome application"
```

Right-to-left `name` in Arabic:

```json
"dir": "rtl",
"lang": "ar",
"name": "!أنا من التطبيق"
```

Specifications
--------------

| Specification |
| --- |
| Web Application Manifest # name-member |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


icons - Web app manifests

icons
=====

|  |  |
| --- | --- |
| Type | `Array` |

The `icons` member specifies an array of objects representing image files that can serve as application icons for different contexts. For example, they can be used to represent the web application amongst a list of other applications, or to integrate the web application with an OS's task switcher and/or system preferences.

Examples
--------

```json
"icons": [
  {
    "src": "icon/lowres.webp",
    "sizes": "48x48",
    "type": "image/webp"
  },
  {
    "src": "icon/lowres",
    "sizes": "48x48"
  },
  {
    "src": "icon/hd\_hi.ico",
    "sizes": "72x72 96x96 128x128 256x256"
  },
  {
    "src": "icon/hd\_hi.svg",
    "sizes": "any"
  }
]
```

Values
------

Image objects may contain the following values:

| Member | Description |
| --- | --- |
| `sizes` |
 A string containing space-separated image dimensions using the same syntax as the
 `sizes`
 attribute.
  |
| `src` |
 The path to the image file. If `src` is a relative URL, the
 base URL will be the URL of the manifest.
  |
| `type` |
 A hint as to the media type of the image. The purpose of this member is
 to allow a user agent to quickly ignore images with media types it does
 not support.
  |
| `purpose` |
 Defines the purpose of the image, for example if the image is intended
 to serve some special purpose in the context of the host OS (i.e., for
 better integration).

`purpose`
 can have one or more of the following values, separated by spaces:
 * `monochrome`: A user agent can present this icon where a
 monochrome icon with a solid fill
 is needed. The color information in the icon is discarded and only
 the alpha data is used. The icon can then be used by the user agent
 like a mask over any solid fill.
* `maskable`: The image is designed with
 icon masks and safe zone
 in mind, such that any part of the image outside the safe zone can
 safely be ignored and masked away by the user agent.
* `any`: The user agent is free to display the icon in any
 context (this is the default value).
 |

Specifications
--------------

| Specification |
| --- |
| Web Application Manifest # icons-member |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


display - Web app manifests

display
=======

|  |  |
| --- | --- |
| Type | `String` |

The `display` member is a string that determines the developers' preferred display mode for the website. The display mode changes how much of browser UI is shown to the user and can range from `browser` (when the full browser window is shown) to `fullscreen` (when the app is fullscreened).

**Note:** The browser follows a pre-defined fallback chain if it does not support a given mode: `fullscreen` → `standalone` → `minimal-ui` → `browser`, with `browser` being the default value if the `display` member is not specified.

**Note:** You can selectively apply CSS to your app based on the display mode, using the `display-mode` media feature. This can be used to provide a consistent user experience between launching a site from a URL and launching it from a desktop icon.

Values
------

The possible values are:

| Display Mode | Description | Fallback Display Mode |
| --- | --- | --- |
| `fullscreen` |
 All of the available display area is used and no user agent
 chrome is shown.
  | `standalone` |
| `standalone` |
 The application will look and feel like a standalone application. This
 can include the application having a different window, its own icon in
 the application launcher, etc. In this mode, the user agent will exclude
 UI elements for controlling navigation, but can include other UI
 elements such as a status bar.
  | `minimal-ui` |
| `minimal-ui` |
 The application will look and feel like a standalone application, but
 will have a minimal set of UI elements for controlling navigation. The
 elements will vary by browser.
  | `browser` |
| `browser` |
 The application opens in a conventional browser tab or new window,
 depending on the browser and platform. This is the default.
  | (None) |

Example
-------

```json
"display": "standalone"
```

Specifications
--------------

| Specification |
| --- |
| Web Application Manifest # display-member |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


theme_color - Web app manifests

theme\_color
============

|  |  |
| --- | --- |
| Type | `String` |

The `theme_color` member is a string that defines the default theme color for the application. This sometimes affects how the OS displays the site (e.g., on Android's task switcher, the theme color surrounds the site).

Examples
--------

```json
"theme\_color": "red"
```

Specifications
--------------

| Specification |
| --- |
| Web Application Manifest # theme\_color-member |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


share_target - Web app manifests

share\_target
=============

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

|  |  |
| --- | --- |
| Type | `Object` |

The `share_target` manifest member allows installed Progressive Web Apps (PWAs) to be registered as a share target in the system's share dialog.

Once registered and installed, a PWA that uses the Web Share Target API acts as a content sharing target, along with typical system share targets like email, messengers, and other native apps that can receive shared content.

**Note:** If you want to share data using the Web Share API, see Web Share API and `navigator.share()`.

Properties
----------

To define how an application can receive share data, a `share_target` object in the manifest may contain the following properties (`action` and `params` are required):

`action`

The URL for the web share target.

`enctype` Optional

The encoding of the share data when a `POST` request is used. Ignored with `GET` requests.

`method` Optional

The HTTP request method to use. Either `GET` or `POST`. Use `POST` if the shared data includes binary data like image(s), or if it changes the target app, for example, if it creates a data point like a bookmark.

`params`

An object to configure the share parameters. The object keys correspond to the `data` object in `navigator.share()`. The object values can be specified and will be used as query parameters:

* `title` Optional: Name of the query parameter to use for the title of the document being shared.
* `text` Optional: Name of the query parameter for the text (or body) of the message being shared.
* `url` Optional: Name of the query parameter for the URL to the resource being shared.
* `files` Optional: An object (or an array of objects) defining which files are accepted by the share target. The object requires the following properties:
    + `name`: Name of the form field used to share files.
    + `accept`: A string (or an array of strings) of accepted MIME types or file extensions.

Examples
--------

### Receiving share data using GET

A share target can be registered using the following `share_target` manifest member:

```json
{
  "share\_target": {
    "action": "/shared-content-receiver/",
    "method": "GET",
    "params": {
      "title": "name",
      "text": "description",
      "url": "link"
    }
  }
}
```

When a user selects your app in the system's share dialog, your PWA is launched, and a `GET` HTTP request is made to the provided URL including the specified query parameters. It will look like this: `/shared-content-receiver/?name=a+shared+name&description=a+shared+description&link=https%3A%2F%2Fexample.com%2F`.

The URLSearchParams interface can be useful to handle the shared data in your application and do something with it.

```js
const sharedName = url.searchParams.get("name");
const sharedDescription = url.searchParams.get("description");
const sharedLink = url.searchParams.get("link");
```

### Receiving share data using POST

If the share request includes one or multiple files or causes a side effect in your application, the HTTP `POST` method should be used. For example, if your application receives images for further processing or wants to save a shared link as a bookmark in your database.

```json
{
  "share\_target": {
    "action": "/save-bookmark/",
    "method": "POST",
    "enctype": "multipart/form-data",
    "params": {
      "url": "link"
    }
  }
}
```

You can either handle `POST` share data using server-side code, or, to provide a better experience for offline users, a `fetch` event listener can be used to intercept the HTTP request which allows to access the data in a service worker.

```js
self.addEventListener("fetch", (event) => {
  // Regular requests not related to Web Share Target.
  if (event.request.method !== "POST") {
    event.respondWith(fetch(event.request));
    return;
  }

  // Requests related to Web Share Target.
  event.respondWith(
    (async () => {
      const formData = await event.request.formData();
      const link = formData.get("link") || "";
      // Instead of the original URL `/save-bookmark/`, redirect
      // the user to a URL returned by the `saveBookmark()`
      // function, for example, `/`.
      const responseUrl = await saveBookmark(link);
      return Response.redirect(responseUrl, 303);
    })(),
  );
});
```

The `POST` request is then ideally replied with an HTTP 303 See Other redirect to avoid multiple `POST` requests from being submitted if a page refresh was initiated by the user, for example.

### Receiving shared files

To accept shared files, the HTTP method must be `POST`, the `enctype` must be `multipart/form-data`, and a `files` entry defining the types of accepted files must be provided.

Files must have a `name` property, and the `accept` property must specify accepted MIME types or file extensions. It's probably a good idea to define both, since operating systems might differ in which they prefer.

```json
{
  "share\_target": {
    "action": "/file-collector",
    "method": "POST",
    "enctype": "multipart/form-data",
    "params": {
      "title": "name",
      "text": "description",
      "url": "link",
      "files": [
        {
          "name": "lists",
          "accept": ["text/csv", ".csv"]
        },
        {
          "name": "photos",
          "accept": ["image/svg+xml", ".svg"]
        }
      ]
    }
  }
}
```

To handle shared file data, see the `POST` example above and the `FileReader` API to read the files. In order to get the files from the service worker context over to client contexts, one solution is to temporarily write the files to the `Cache` or IndexedDB and then notify its clients using `Client.postMessage()`.

Security & Privacy
------------------

Your PWA can only act as a web share target if it has been installed. See also How to make PWAs installable.

Similar to HTML form submissions, you should be cautious about data that is sent to your application via the share target. Be sure to validate incoming data before using it.

Specifications
--------------

| Specification |
| --- |
| Web Share Target API # share\_target-member |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


file_handlers - Web app manifests

file\_handlers
==============

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

|  |  |
| --- | --- |
| Type | `Array` |

The `file_handlers` member specifies an array of objects representing the types of files an installed progressive web app (PWA) can handle.

The `file_handlers` member is read by the browser when the PWA is installed and used to associate the application with a given set of file types at the operating system level.

For example, a PWA can be registered to handle files that match the `text/plain` MIME type. Once this PWA is installed, the operating system is able to use it to handle text files, opening the PWA when the user opens a file of this type. Note that other applications may also be registered as text file handlers, and the way operating systems manage the association between file types and applications, and the way they let users choose an application to handle a given file can vary from one device to another.

**Note:** While the `file_handlers` member is used to register a PWA with a given set of file types, this only results in the operating system launching the PWA when a matching file is opened. The PWA then needs to actually handle the file using JavaScript code. See Handling the files for more information.

Values
------

An array of objects. Each object in the array must contain the following values (`action` and `accept` are required):

| Member | Description |
| --- | --- |
| `action` | A string containing the URL to navigate to when a file is handled.This URL must be within the navigation scope of the PWA, which is the set of URLs that the PWA can navigate to. The navigation scope of a PWA defaults to its `start_url` member, but can also be defined by using the `scope` member. |
| `accept` | An object. For each property in the object:
 * The property key is a MIME type.
* The property value is an array of strings representing file extensions associated with that MIME type.
 |

Example
-------

In this example, a web app manifest declares one file handler that registers the app to handle audio files. Other manifest members such as `name`, or `icons` are not included in this example for brevity:

```json
{
  "file\_handlers": [
    {
      "action": "/handle-audio-file",
      "accept": {
        "audio/wav": [".wav"],
        "audio/x-wav": [".wav"],
        "audio/mpeg": [".mp3"],
        "audio/mp4": [".mp4"],
        "audio/aac": [".adts"],
        "audio/ogg": [".ogg"],
        "application/ogg": [".ogg"],
        "audio/webm": [".webm"],
        "audio/flac": [".flac"],
        "audio/mid": [".rmi", ".mid"]
      }
    }
  ]
}
```

### Handling the files

To actually implement file handling in a PWA, web developers also need to use `window.launchQueue` to handle the incoming files in their application JavaScript code.

Handling files is done in the application code that runs on the main thread, not in the application's service worker.

In the following example, `window.launchQueue.setConsumer()` is used to specify a callback function that receives incoming audio files and plays the first one using an `Audio` element:

```js
async function playSong(handledFile) {
  const blob = await handledFile.getFile();
  const url = window.URL.createObjectURL(blob);
  const audio = new Audio(url);
  audio.play();
}

if ("launchQueue" in window) {
  window.launchQueue.setConsumer((launchParams) => {
    if (launchParams.files && launchParams.files.length) {
      playSong(launchParams.files[0]);
    }
  });
}
```

Specifications
--------------

| Specification |
| --- |
| Manifest Incubations # file\_handlers-member |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Handle files in Progressive Web Apps on learn.microsoft.com
* Let installed web applications be file handlers on developer.chrome.com


orientation - Web app manifests

orientation
===========

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

|  |  |
| --- | --- |
| Type | `String` |

The `orientation` member defines the default orientation for all the website's top-level browsing contexts.

**Note:** `orientation` and/or its specific values might not be supported by a user agent on various display modes because supporting them does not make sense for the particular context.

**Note:** The orientation can be changed at runtime via the Screen Orientation API.

Values
------

`orientation` can take one of the following values:

* `any`
* `natural`
* `landscape`
* `landscape-primary`
* `landscape-secondary`
* `portrait`
* `portrait-primary`
* `portrait-secondary`
Examples
--------

```json
"orientation": "portrait-primary"
```

Specifications
--------------

| Specification |
| --- |
| Web Application Manifest # orientation-member |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


prefer_related_applications - Web app manifests

prefer\_related\_applications
=============================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

|  |  |
| --- | --- |
| Type | `Boolean` |

The `prefer_related_applications` member is a boolean value that specifies that applications listed in `related_applications` should be preferred over the web application. If the `prefer_related_applications` member is set to `true`, the user agent might suggest installing one of the related applications instead of this web app.

If omitted, `prefer_related_applications` defaults to `false`.

Examples
--------

```json
"prefer\_related\_applications": true
```

Specifications
--------------

| Specification |
| --- |
| Web Application Manifest # prefer\_related\_applications-member |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Timeouts - WebDriver

Timeouts
========

Associated with a WebDriver session are various timeout definitions that control behavior for script injection, document navigation, and element retrieval.

You will find the *timeouts object* used in a few different contexts. It can be used as configuration when creating a new session through capabilities, it is returned as part of the matched, effective capabilities after the session has been created, and it is used as input and output for the Set Timeouts and Get Timeouts commands.

The default values can be overridden when creating the session and they will be effective until the session is closed. If you call Set Timeouts during the session's lifetime, the defaults are overridden and will take effect for the lifetime of the session or until Set Timeouts is called again.

Payload
-------

The **timeouts object** is a JSON Object that either describes the current session's timeout values, or which is used as input when configuring the timeouts:

`implicit`

Time in milliseconds to retry the element location strategy when finding an element. This defaults to 0, meaning the strategy is run only once.

`pageLoad`

Time in milliseconds to wait for the document to finish loading. By default WebDriver will wait five minutes (or 300,000 ms).

`script`

Scripts injected with Execute Script or Execute Async Script will run until they hit the script timeout duration, which is also given in milliseconds. The scripts will then be interrupted and a script timeout error will be returned. Defaults to 30 seconds (or 30,000 ms).

When the object is used as input for the Set Timeouts command or as part of the timeouts capability when creating a new session, all fields are optional. This means you can configure zero or more of the timeout duration values individually or all at once.

When it is returned by the driver, either by Get Timeouts or in the matched capabilities from having created a session, all fields will be present.

Examples
--------

### Setting timeouts at session creation

You can override the default session timeouts by providing a timeouts capabilities object when you start a new WebDriver session:

```python
import urllib

from selenium import webdriver

def inline(doc):
    return "data:text/html;charset=utf-8,{}".format(urllib.quote(doc))

session = webdriver.Firefox(capabilities={"timeouts": {"implicit": 4500}})
session.get(inline("""
 <h1>Example</h1>

 <script>
 // Inserts <p> below <h1> after 2.5 seconds:
 setTimeout(() => {
 const delayedElement = document.createElement("p");
 const h1 = document.querySelector("h1");
 document.body.insertAfter(delayedElement, h1);
 }, 2500);
 </script>
 """)

# This will cause the driver to wait 4.5 seconds
# for #foo to appear in the DOM:
delayed_element = session.find_element_by_tag_name("p")
```

### Setting and getting timeouts at runtime

Timeouts can also be set at runtime using the Set Timeouts command. These will override the session's current timeouts and will take effect for the entire lifetime of the session or until a subsequent call is made to the same command:

```python
from selenium import webdriver

session = webdriver.Firefox()

session.set_timeouts({"implicit": 4.5})
print(session.get_timeouts)
```

The output will be in seconds because this is the idiomatic time unit in Python:

```json
{ "implicit": 4.5, "script": 300, "pageLoad": 30000 }
```


Commands - WebDriver

Commands
========

The following is a list of the available WebDriver commands.

Close WindowThe *Close Window* command of the WebDriver API closes the current top-level browsing context (window or tab) and returns with the list of currently open `WebWindow`s. If it is the last window that is being closed, the WebDriver session will implicitly be deleted. Subsequent commands after the session is ended will therefore cause invalid session ID errors.

Get Element AttributeThe *Get Element Attribute* command of the WebDriver API returns the attribute of the referenced web element. If for example the element is an `img`, the returned attribute is `"//TODO"`, which is equivalent to calling `Element.getAttribute` on the element. For XML/XHTML documents it may be cased differently.

Get Element PropertyThe *Get Element Property* command of the WebDriver API returns the property of the referenced web element. Given `<input value=foo>` where the user changes the value to `bar`, the returned property is `bar` rather than the initial value `foo`. This is equivalent to calling `Element.getProperty` on the element.

Get Element Tag NameThe *Get Element Tag Name* command of the WebDriver API returns the tag name of the referenced web element. If for example the element is an `img`, the returned tag name is `"IMG"`, which is equivalent to calling `Element.tagName` on the element. For XML/XHTML documents it may be cased differently.

Get TimeoutsThe *Get Timeouts* command of the WebDriver API returns the timeouts associated with the current session. The session timeout durations control such behavior as timeouts on script injection, document navigation, and element retrieval.

Get Window HandlesThe *Get Window Handles* command of the WebDriver API returns a list of all `WebWindow`s. Each tab or window, depending on whether you are using a tabbed browser, is associated by a *window handle* that is used as a reference when switching to the window.

Get Window RectThe *Get Window Rect* command of the WebDriver API returns the size and position of the given `WebElement`. Many WebDriver clients present separate API methods for getting an element's location and dimensions, but as an optimization they both use this primitive.

New WindowThe *New Window* command of the WebDriver API opens a new top-level browsing context of type *window* or *tab*, and returns with a dictionary containing the *handle* of the new WebWindow and its created *type*. If the requested *type* cannot be created by the browser, the alternative type will be tried to create.

Set TimeoutsThe *Set Timeouts* command of the WebDriver API sets the timeouts associated with the current session. The session timeout durations control such behavior as timeouts on script injection, document navigation, and element retrieval.

Set Window RectThe *Set Window Rect* command of the WebDriver API alters the size and position of the operating system window associated with the current `window`. The command acts as the setter of Get Window Rect, which return object you can pass directly as this command's payload.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


WebDriver errors - WebDriver

WebDriver errors
================

Any WebDriver command that is sent to might plausibly receive an error response. An error is represented by an HTTP response with an HTTP status code in the 4xx or 5xx range, and a JSON payload holding details of the error.

Payload
-------

The **error object** is a JSON Object that bears three, and sometimes four, fields:

`error`

Error type.

`message`

Human-readable description of the nature of the error.

`stacktrace`

Stacktrace report of the active stack frames at the time when the error occurred.

`data` (optional)

Arbitrary and implementation-defined data that it can be useful to present the user with.

Many drivers include the user prompt's text when encountering an unexpected alert open error.

Example
-------

For example a `GET` request to `/session/1234/url`, where `1234` is a bogus session, would return a response with the `404 Not Found` status and the following body:

```json
{
  "value": {
    "error": "invalid session id",
    "message": "No active session with ID 1234",
    "stacktrace": ""
  }
}
```

It is optional for the driver to annotate errors with additional error data. Notably, this is common when a user prompt, such as `window.alert`, has opened a modal dialog after execution of your previous WebDriver command request.

Because both WebDriver and JavaScript execution is halted by such a dialog, we see an unexpected alert open error in the subsequent response:

```json
{
  "value": {
    "error": "unexpected alert open",
    "message": "",
    "stacktrace": "",
    "data": {
      "text": "Message from window.alert"
    }
  }
}
```

In most clients the error would be represented by some sort of error *type* or *object representation*. In Python it is represented as a `WebDriverException`, in Node.js as a `WebDriverError`, and in Java also as a `WebDriverException`.

Table of errors
---------------

| Error type | HTTP status code | Description |
| --- | --- | --- |
| element click intercepted | `400 Bad Request` | The Element Click command could not be completed because the element receiving the events is obscuring the element that was requested clicked. |
| element not interactable | `400 Bad Request` | A command could not be completed because the element is not pointer- or keyboard interactable. |
| insecure certificate | `400 Bad Request` | Navigation caused the user agent to hit a certificate warning, which is usually the result of an expired or invalid TLS certificate. |
| invalid argument | `400 Bad Request` | The arguments passed to a command are either invalid or malformed. |
| invalid cookie domain | `400 Bad Request` | An illegal attempt was made to set a cookie under a different domain than the current page. |
| invalid element state | `400 Bad Request` | A command could not be completed because the element is in an invalid state, e.g. attempting to clear an element that isn't both editable and resettable. |
| invalid selector | `400 Bad Request` | An element retrieval command provided an unknown selector strategy. |
| invalid session id | `404 Not Found` | Given session ID is not recognized, meaning the session either does not exist of that it's not active. Note that a session that has been deleted cannot be re-used. |
| JavaScript error | `500 Internal Server Error` | An error occurred while executing JavaScript supplied by the user. |
| move target out of bounds | `500 Internal Server Error` | The target for mouse interaction is not in the browser's viewport and cannot be brought into that viewport. |
| no such alert | `404 Not Found` | An attempt was made to operate on a user prompt when one was not open. |
| no such cookie | `404 Not Found` | No cookie matching the given path name was found amongst the cookies of the current document. |
| no such element | `404 Not Found` | An element could not be located on the page using the given search parameters. |
| no such frame | `404 Not Found` | A command to switch to a frame could not be satisfied because the frame could not be found. |
| no such window | `404 Not Found` | A command to switch to a window could not be satisfied because the window could not be found. |
| script timeout | `408 Request Timeout` | A script did not complete before its timeout expired. |
| session not created | `500 Internal Server Error` | A new session could not be created, either because the browser could not be started or because the provided capabilities to start the session did not match. |
| stale element reference | `404 Not Found` | A command failed because the referenced element is no longer attached to the DOM. |
| timeout | `408 Request Timeout` | An operation did not complete before its timeout expired. |
| unable to set cookie | `500 Internal Server Error` | A command to set a cookie's value could not be satisfied. |
| unable to capture screen | `500 Internal Server Error` | A screen capture was made impossible. |
| unexpected alert open | `500 Internal Server Error` | A modal dialog was open, blocking this operation. |
| unknown command | `404 Not Found` | A command could not be executed because the driver was unaware of it. |
| unknown error | `500 Internal Server Error` | An unknown error occurred in the driver whilst processing the command. |
| unknown method | `405 Method Not Allowed` | The requested command matched a known URL but did not match a method for that URL. |
| unsupported operation | `500 Internal Server Error` | Indicates that a command that should have executed properly cannot be supported for some reason. |

See also
--------

* WebDriver responses
* WebDriver commands


Capabilities - WebDriver

Capabilities
============

WebDriver ***capabilities*** are used to communicate the features supported by a session. A client may also use capabilities to define which features it requires the driver to satisfy when creating a new session.

When a WebDriver session is created it returns a set of capabilities describing the negotiated, effective capabilities of the session. Some of the capabilities included in this set are standard and shared between all browsers, but the set may also contain browser-specific capabilities and these are always prefixed.

Capabilities negotiation
------------------------

Capabilities can be used to require a driver that supports a certain subset of features. This can be used to require certain browser features, such as the ability to resize the window dimensions, but is also used in distributed environments to select a particular browser configuration from a matrix of choices.

Selecting a particular web browser or platform only makes sense when you use a remote WebDriver. In this case the client makes contact with WebDriver through one or more intermediary nodes which negotiates which driver to return to you based on the capabilities it receives.

The capabilities object is a selection mechanism that limits which driver configurations the server will return. If you request a Firefox instance using `browserName` and Firefox is not installed on the remote, or macOS from a remote that only supports Linux, you may be out of luck. But occasionally you may not care which specific operating system or web browser your session has: you just want a session that has some *capability*.

The selection process, or the *capabilities negotiation*, is done through `alwaysMatch` and `firstMatch`.

### `alwaysMatch`

As the name suggests, capabilities described inside the `alwaysMatch` capabilities object are features you *require* the session to have. If the server can not provide what features you require, it will fail.

If for example you ask for Firefox version 62 on a system that only has 60 installed, the session creation will fail:

```json
{
  "capabilities": {
    "alwaysMatch": {
      "browserName": "firefox",
      "browserVersion": "60"
    }
  }
}
```

### `firstMatch`

The `firstMatch` field accepts *an array* of capabilities objects which will be matched in turn until one matches what the server can provide, or it will fail.

This can be useful when you want a driver that runs on macOS or Linux, but not Windows:

```json
{
  "capabilities": {
    "firstMatch": [{ "platformName": "macos" }, { "platformName": "linux" }]
  }
}
```

### Combining `alwaysMatch` and `firstMatch`

`firstMatch` can of course be combined with `alwaysMatch` to narrow down the selection. If for example you a driver that runs on macOS or Linux but it *has* to be Firefox:

```json
{
  "capabilities": {
    "alwaysMatch": {
      "browserName": "firefox"
    },
    "firstMatch": [{ "platformName": "macos" }, { "platformName": "linux" }]
  }
}
```

The previous example is exactly equivalent to putting the Firefox requirement in each `firstMatch` arm:

```json
{
  "capabilities": {
    "firstMatch": [
      { "browserName": "firefox", "platformName": "macos" },
      { "browserName": "firefox", "platformName": "linux" }
    ]
  }
}
```

Which you choose of the two preceding examples is not important, but it can matter when pass along browser configuration. To avoid unnecessarily repeating data, such as profiles, it is advisable to make use of `alwaysMatch` so that this data is only transmitted across the wire once:

```json
{
  "capabilities": {
    "alwaysMatch": {
      "browserName": "firefox",
      "moz:firefoxOptions": {
        "profile": "<base64 encoded profile>",
        "args": ["-headless"],
        "prefs": { "dom.ipc.processCount": 8 },
        "log": { "level": "trace" }
      }
    },
    "firstMatch": [{ "platformName": "macos" }, { "platformName": "linux" }]
  }
}
```

List of capabilities
--------------------

* `browserName`
* `browserVersion`
* `platformName`
* `acceptInsecureCerts`: This capability communicates whether expired or invalid TLS certificates are checked when navigating. If the capability is false, an insecure certificate error will be returned as navigation encounters domains with certificate problems. Otherwise, self-signed or otherwise invalid certificates will be implicitly trusted by the browser on navigation. The capability has effect for the lifetime of the session.
* `pageLoadStrategy`
* `proxy`
* `setWindowRect`
* `timeouts`
* `unhandledPromptBehavior`
Vendor-specific capabilities
----------------------------

In addition to the standard capabilities WebDriver allows third-parties to *extend* the set of capabilities to match their needs. Browser vendors and suppliers of drivers typically use extension capabilities to provide configuration to the browser, but they can also be used by intermediaries for arbitrary blobs of information.

* Firefox capabilities (`moz:firefoxOptions`)
* Chrome capabilities (`goog:chromeOptions`)
Legacy capabilities
-------------------

The majority of Selenium clients use `desiredCapabilities` and `requiredCapabilities` to configure the new session. These are very similar to `firstMatch` and `alwaysMatch` described above. Some drivers support these legacy capabilities, but they are deprecated and should be avoided.

Converting a legacy capabilities object into the new style is easy. The first thing you need to know is that `alwaysMatch`/`firstMatch` is *always* wrapped inside a `capabilities` JSON Object, whereas `desiredCapabilities`/`requiredCapabilities` exists at the top level. Generally speaking, anything that has previously gone in `desiredCapabilities` should go in a `firstMatch` branch arm to achieve the same effect.

Take this deprecated capabilities object:

```json
{ "desiredCapabilities": { "browserName": "firefox" } }
```

This would be functionally equivalent in the new style:

```json
{ "capabilities": { "firstMatch": [{ "browserName": "firefox" }] } }
```

But because there is only one `firstMatch` arm, and we know that session creation will fail if the server doesn't have a Firefox installed, it is also equivalent to this:

```json
{ "capabilities": { "alwaysMatch": { "browserName": "firefox" } } }
```

See also
--------

* New Session command
* Delete Session command


firefoxOptions - WebDriver

firefoxOptions
==============

 The **`moz:firefoxOptions` capability** is a namespaced set of
 capabilities specific to Firefox. It is used to control the
 behavior of Firefox and can be used as a member of
 `alwaysMatch` or as a member of one of the
 `firstMatch` entries.

It is used to define options which control how Firefox gets started and run.

`moz:firefoxOptions` is a JSON Object which may contain any of the following fields:

##### `binary` (string)

Absolute path to the custom Firefox binary to use.

 On macOS you may either give the path to the application bundle, i.e. `/Applications/Firefox.app`, or the
 absolute path to the executable binary inside this bundle, for example
 `/Applications/Firefox.app/Contents/MacOS/firefox-bin`.

 geckodriver will attempt to deduce the default location of Firefox on the current system if left undefined. The
 default locations of Firefox are:

| System | Default location |
| --- | --- |
| macOS | 1. `/Applications/Firefox.app/Contents/MacOS/firefox-bin`
2. `$HOME/Applications/Firefox.app/Contents/MacOS/firefox-bin`
 |
| LinuxBSD |
 First `firefox` found on the system path. This is
 equivalent to the output of running
 which(1):

```

% which firefox
/usr/bin/firefox
```

 |
| Windows | From the Window system registry:1. `HKEY_LOCAL_MACHINE\SOFTWARE WOW6432Node\Mozilla\Mozilla
Firefox\[VERSION]\Main\PathToExe`
2. `HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Mozilla
Firefox\[VERSION]\Main\PathToExe`
 |

##### `args` (array of strings)

 Command line arguments to pass to the Firefox binary. These must include the leading dash (`-`) where
 required, e.g. `["-headless"]`.

 To have geckodriver pick up an existing profile on the local filesystem, you may pass
 `["-profile", "/path/to/profile"]`. But if a profile has to be transferred to a target machine it is
 recommended to use the `profile` entry.

##### `profile` (string)

 Base64-encoded ZIP of a profile directory to use for the Firefox instance. This may be used to e.g. install
 extensions or custom certificates, but for setting custom preferences we recommend using the `prefs` (Preferences Object) entry instead.

 Profiles are created in the systems temporary folder. This is also where the encoded profile is extracted when
 `profile` is provided. By default geckodriver will create a new profile in this location.

 The effective profile in use by the WebDriver session is returned to the user in the `moz:profile`
 capability in the new session response.

 To have geckodriver pick up an existing profile on the filesystem, please set the `args` field to
 `{"args": ["-profile", "/path/to/your/profile"]}`. Note that if you use a remote client targeting a server
 on a different system, the profile must already exist on the target system.

##### `log` (Log object)

 To increase the logging verbosity of geckodriver and Firefox, you may pass a `log`
 object that may look like `{"log": {"level": "trace"}}` to include all trace-level logs and above

##### `prefs` (Preferences object)

Map of preference name to preference value, which can be a string, a boolean or an integer.

##### `env` (Env object)

Map of environment variable name to environment variable value, both of which must be strings.

### Android

Starting with geckodriver 0.26.0 additional capabilities exist if Firefox or an application embedding GeckoView has to be controlled on Android:

#### `androidPackage` (string, required)

 The package name of Firefox, e.g. `org.mozilla.firefox`,
 `org.mozilla.firefox_beta,` or `org.mozilla.fennec` depending on the release
 channel, or the package name of the application embedding GeckoView, e.g. `org.mozilla.geckoview_example`.

#### `androidActivity` (string, optional)

 The fully qualified class name of the activity to be launched, e.g. `.GeckoViewActivity`. If not
 specified, the package's default activity will be used.

#### `androidDeviceSerial` (string, optional)

 The serial number of the device on which to launch the application. If not specified and multiple devices are
 attached, an error will be returned.

#### `androidIntentArguments` (array of strings, optional)

 Arguments to launch the intent with. Under the hood, geckodriver uses Android am to start the Android application
 under test. The given intent arguments are appended to the `am start` command. See Android's specification for intent arguments for
 details. This allows to control how the application is launched and to include optional extras for enabling and
 disabling features. For example, to launch with the view action and a specified URL before navigating as part of a
 test, include:

```json
{
  "androidIntentArguments": [
    "-a",
    "android.intent.action.VIEW",
    "-d",
    "https://example.com"
  ]
}
```

For example, to specify a boolean extra that can be processed with android.content.Intent.getBooleanExtra, include:

```json
{
  "androidIntentArguments": ["--ez", "customBooleanFlagName", "true"]
}
```

### Log object

A JSON Object that may have any of these fields:

#### `level` (string)

 Set the level of verbosity of geckodriver and Firefox. Available levels are `trace`, `debug`,
 `config`, `info`, `warn`, `error`, and `fatal`. If left
 undefined the default is `info`. The value is treated case-insensitively.

### Preferences object

 A JSON Object with one entry per preference to set. The preference will be written to the profile before starting Firefox. A full list of available preferences is available from visiting
 "about:config" in your Firefox browser. Some of these are documented in this source file.

An example of a preference object:

```json
{
  "dom.ipc.processCount": 8,
  "javascript.options.showInConsole": false
}
```

### Env object

 A JSON Object with one entry per environment variable to set. On Desktop, the Firefox under test will launch with
 given variable in its environment. On Android, the GeckoView-based App will have the given variable added to the
 `env` block in its configuration YAML.

An example of an env object:

```json
{
  "MOZ\_LOG": "nsHttp:5",
  "MOZ\_LOG\_FILE": "/mnt/sdcard/log"
}
```

Example
-------

 The following is an example of a full capabilities object that
 selects a specific Firefox binary to run with a prepared profile from the filesystem in headless mode. It also increases the number of IPC processes
 through a preference, turns off chrome errors/warnings in the console, and enables more verbose logging:

```json
{
  "capabilities": {
    "alwaysMatch": {
      "moz:firefoxOptions": {
        "binary": "/usr/local/firefox/bin/firefox",
        "args": ["-headless", "-profile", "/path/to/my/profile"],
        "prefs": {
          "dom.ipc.processCount": 8,
          "javascript.options.showInConsole": false
        },
        "log": { "level": "trace" },
        "env": {
          "MOZ\_LOG": "nsHttp:5",
          "MOZ\_LOG\_FILE": "/path/to/my/profile/log"
        }
      }
    }
  }
}
```

 The `moz:firefoxOptions` must be placed—as above—inside
 `alwaysMatch`, or in one of the
 `firstMatch` capabilities objects as seen here:

```json
{
  "capabilities": {
    "firstMatch": [
      {"moz:firefoxOptions": …}
    ]
  }
}
```

### Android

This runs the GeckoView example application as installed on the first Android emulator running on the host machine:

```json
{
  "capabilities": {
    "alwaysMatch": {
      "moz:firefoxOptions": {
        "androidPackage": "org.mozilla.geckoview\_example",
        "androidActivity": "org.mozilla.geckoview\_example.GeckoView",
        "androidDeviceSerial": "emulator-5554",
        "androidIntentArguments": ["-d", "http://example.org"],
        "env": {
          "MOZ\_LOG": "nsHttp:5",
          "MOZ\_LOG\_FILE": "/mnt/sdcard/log"
        }
      }
    }
  }
}
```

See also
--------

* geckodriver's documentation on supported Firefox capabilities
* Chrome-specific WebDriver capabilities
 (`goog:chromeOptions)`
* List of WebDriver capabilities
* New Session command


webSocketUrl - WebDriver

webSocketUrl
============

 With the `webSocketUrl` capability set to `true` a WebSocket server will be started in the browser, supporting bidirectional communication by using the WebDriver BiDi protocol.
 When the New Session request has the `webSocketUrl` capability set to `true`, and the session starts successfully, the value of the `capabilities` field in the response will have a `webSocketUrl` property set to the URL of the WebSocket server.

Example
-------

Requesting the WebSocket URL by setting the `webSocketUrl` capability to `true`:

Request:

```http
POST /session HTTP/1.1
{"capabilities": {"alwaysMatch": {"webSocketUrl": true}}}
```

Response:

```json
{"value":{"capabilities":{"webSocketUrl":"ws://localhost:9222/session/571f206f-c3fe-794c-9218-77fa89595eb9", [..]}, "sessionId":"571f206f-c3fe-794c-9218-77fa89595eb9"}}
```

See also
--------

* List of WebDriver capabilities
* New Session command
* Establishing a WebDriver BiDi connection


acceptInsecureCerts - WebDriver

acceptInsecureCerts
===================

The **`acceptInsecureCerts` capability** communicates whether expired or invalid TLS certificates are checked when navigating. When the capability is false, an insecure certificate error will be returned as navigation encounters domains with certificate problems. Otherwise, self-signed or otherwise invalid certificates will be implicitly trusted by the browser on navigation. The capability has effect for the lifetime of the session.

Example
-------

Using the `acceptInsecureCerts` capability you can bypass, or implicitly trust, TLS certificates that the certificate service in the browser does not trust:

```python
from selenium import webdriver
from selenium.common import exceptions

session = webdriver.Firefox(capabilities={"acceptInsecureCerts": True})
session.get("https://self-signed.badssl.com/")
print(session.current_url)
```

Output:

```url
https://self-signed.badssl.com/
```

See also
--------

* List of WebDriver capabilities
* Navigate To command
* New Session command


Get Element Attribute - WebDriver

Get Element Attribute
=====================

The *Get Element Attribute* command of the WebDriver API returns the attribute of the referenced web element. If for example the element is an `<img>`, the returned attribute is `"//TODO"`, which is equivalent to calling `Element.getAttribute` on the element. For XML/XHTML documents it may be cased differently.

Syntax
------

| Method | URI template |
| --- | --- |
| `GET` | `/session/{session id}/element/{element id}/attribute/{name}` |

### URL parameters

`session id`

Identifier of the session.

`element id`

Identifier of the web element to get the tag name of.

`name`

Identifier of the attribute of web element to get.

### Errors

Session not created

Session does not exist.

No such window

The `window` object has been discarded, indicating that the tab or window has been closed.

Unexpected alert open

A user prompt, such as `window.alert`, blocks execution of command until it is dealt with.

Examples
--------

Python:

```python
from selenium import webdriver

session = webdriver.Firefox()
session.get("https://google.com/?hl=en")
search_box = session.find_element_by_id("q")

print(search_box.get_attribute("id"))
```

Output:
```

q
```

Specifications
--------------

| Specification |
| --- |
| WebDriver # dfn-get-element-attribute |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Get Timeouts - WebDriver

Get Timeouts
============

The *Get Timeouts* command of the WebDriver API returns the timeouts associated with the current session. The session timeout durations control such behavior as timeouts on script injection, document navigation, and element retrieval.

Syntax
------

| Method | URI template |
| --- | --- |
| `GET` | `/session/{session id}/timeouts` |

### URL parameters

`session id`

Identifier of the session.

### Response

The response payload is a `Timeouts` object:

`implicit`

Time in milliseconds to retry the element location strategy when finding an element. This defaults to 0, meaning the strategy is run only once.

`pageLoad`

Time in milliseconds to wait for the document to finish loading. By default WebDriver will wait five minutes (or 300,000 ms).

`script`

Scripts injected with Execute Script or Execute Async Script will run until they hit the script timeout duration, which is also given in milliseconds. The scripts will then be interrupted and a script timeout error will be returned. Defaults to 30 seconds (or 30,000 ms).

### Errors

Invalid session ID

Session does not exist.

Specifications
--------------

| Specification |
| --- |
| WebDriver # dfn-get-timeouts |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Timeouts` object
* Set Timeouts command
* List of WebDriver commands


Get Window Rect - WebDriver

Get Window Rect
===============

The *Get Window Rect* command of the WebDriver API returns the size and position of the given `WebElement`. Many WebDriver clients present separate API methods for getting an element's location and dimensions, but as an optimization they both use this primitive.

The command operates on the currently selected window, and returns size and position of the operating system window. The returned `WindowRect` can be used as input for the Set Window Rect command, which is for manipulating a window's position and dimensions.

Syntax
------

| Method | URI template |
| --- | --- |
| `GET` | `/session/{session id}/window/rect` |

### URL parameters

`session id`

Identifier of the session.

### Response

The response payload is a `WindowRect`:

`x`

Horizontal position of the operating system window associated with `window`, equivalent to `Window.screenX`.

`y`

Vertical position of the operating system window associated with `window`, equivalent to `Window.screenY`.

`width`

Width of outer bounds of the operating system window associated with `window`, equivalent to `Window.outerWidth`.

`height`

Height of the outer bounds of the operating system window associated with `window`, equivalent to `Window.outerHeight`.

### Errors

Invalid session ID

Session does not exist.

Unexpected alert open

A user prompt, such as `window.alert`, blocks execution of command until it is dealt with.

Specifications
--------------

| Specification |
| --- |
| WebDriver # dfn-get-window-rect |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebWindow
* Associated commands:
    + Set Window Rect
    + Get Window Handle
    + Get Window Handles
    + Close Window


Get Window Handles - WebDriver

Get Window Handles
==================

The *Get Window Handles* command of the WebDriver API returns a list of all `WebWindow`s. Each tab or window, depending on whether you are using a tabbed browser, is associated by a *window handle* that is used as a reference when switching to the window.

In order to determine whether or not a particular interaction with the browser opens a new window, one can obtain the set of window handles before the interaction is performed and compare it with the set after the action is performed.

Syntax
------

| Method | URI template |
| --- | --- |
| `GET` | `/session/{session id}/window/handles` |

### URL parameters

`session id`

Identifier of the session.

### Errors

Invalid session ID

Session does not exist.

Example
-------

C#:

```cpp
using System.Collections.ObjectModel;
using OpenQA.Selenium.Firefox;

namespace MDNWebDriverExamples
{
    class Example
    {
        public static void Main(string[] args)
        {
            FirefoxDriver session = new FirefoxDriver();

            session.ExecuteScript("window.open()");

            ReadOnlyCollection<string> currentWindowHandles = session.WindowHandles;
        }
    }
}
```

Specifications
--------------

| Specification |
| --- |
| WebDriver # dfn-get-window-handles |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Switch To Window command
* Get Window Handle command
* Close Window command


Get Element Property - WebDriver

Get Element Property
====================

The *Get Element Property* command of the WebDriver API returns the property of the referenced web element. Given `<input value=foo>` where the user changes the value to `bar`, the returned property is `bar` rather than the initial value `foo`. This is equivalent to calling `Element.getProperty` on the element.

Syntax
------

| Method | URI template |
| --- | --- |
| `GET` | `/session/{session id}/element/{element id}/property/{name}` |

### URL parameters

`session id`

Identifier of the session.

`element id`

Identifier of the web element to get the tag name of.

`name`

Identifier of the property of web element to get.

### Errors

Session not created

Session does not exist.

No such window

The `window` object has been discarded, indicating that the tab or window has been closed.

Unexpected alert open

A user prompt, such as `window.alert`, blocks execution of command until it is dealt with.

Examples
--------

Python:

```python
import urllib

from selenium import webdriver

def inline(doc):
    return "data:text/html;charset=utf-8,{}".format(urllib.quote(doc))

session = webdriver.Firefox()
session.get(inline("<input value=foo>"))
textbox = driver.find_element_by_tag_name("input")
textbox.send_keys("bar")

print(text_box.get_attribute("value"))
print(text_box.get_property("value"))
```

Output:
```

foo
bar
```

Specifications
--------------

| Specification |
| --- |
| WebDriver # dfn-get-element-property |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Get Element Attribute command
* *What is the difference between properties and attributes?* on Stack Overflow


Get Element Tag Name - WebDriver

Get Element Tag Name
====================

The *Get Element Tag Name* command of the WebDriver API returns the tag name of the referenced web element. If for example the element is an `<img>`, the returned tag name is `"IMG"`, which is equivalent to calling `Element.tagName` on the element. For XML/XHTML documents it may be cased differently.

Syntax
------

| Method | URI template |
| --- | --- |
| `GET` | `/session/{session id}/element/{element id}/name` |

### URL parameters

`session id`

Identifier of the session.

`element id`

Identifier of the web element to get the tag name of.

### Errors

Session not created

Session does not exist.

No such window

The `window` object has been discarded, indicating that the tab or window has been closed.

Unexpected alert open

A user prompt, such as `window.alert`, blocks execution of command until it is dealt with.

Examples
--------

Python:

```python
from selenium import webdriver

session = webdriver.Firefox()
session.get("https://google.com/?hl=en")
search_box = driver.find_element_by_id("q")

print(search_box.tag_name)
```

Output:
```

INPUT
```

Specifications
--------------

| Specification |
| --- |
| WebDriver # dfn-get-element-tag-name |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Close Window - WebDriver

Close Window
============

The *Close Window* command of the WebDriver API closes the current top-level browsing context (window or tab) and returns with the list of currently open `WebWindow`s. If it is the last window that is being closed, the WebDriver session will implicitly be deleted. Subsequent commands after the session is ended will therefore cause invalid session ID errors.

Syntax
------

| Method | URI template |
| --- | --- |
| `DELETE` | `/session/{session id}/window` |

### URL parameters

`session id`

Identifier of the session.

### Errors

Invalid session ID

Session does not exist.

Unexpected alert open

A user prompt, such as `window.alert`, blocks execution of command until it is dealt with.

Example
-------

Python:

```python
from selenium import webdriver

session = webdriver.Firefox()
original_window = session.window_handle

new_window = session.execute_script("return window.open()")
session.switch_to.window(new_window)

session.close()
session.switch_to.window(original_window)
```

C#:

```cpp
using OpenQA.Selenium.Firefox;

namespace MDNWebDriverExamples
{
    class Example
    {
        public static void Main(string[] args)
        {
            FirefoxDriver session = new FirefoxDriver();
            string original_window = session.CurrentWindowHandle;// Optional if you want to store the handle in a variable

            session.ExecuteScript("window.open()");
            session.SwitchTo().Window(session.WindowHandles[1]); // Switch to the second window

            session.Close(); // Close current window
            session.SwitchTo().Window(session.WindowHandles[0]); // Switch back to the first window
        }
    }
}
```

Specifications
--------------

| Specification |
| --- |
| WebDriver # dfn-close-window |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Switch To Window command
* Get Window Handle command
* Get Window Handles command


New Window - WebDriver

New Window
==========

The *New Window* command of the WebDriver API opens a new top-level browsing context of type *window* or *tab*, and returns with a dictionary containing the *handle* of the new WebWindow and its created *type*. If the requested *type* cannot be created by the browser, the alternative type will be tried to create.

Syntax
------

| Method | URI template |
| --- | --- |
| `POST` | `/session/{session id}/window/new` |

### URL parameters

`session id`

Identifier of the session.

### Payload

The input is an object:

`type`

Requested type of top-level browsing context.

### Response

The response payload is an object:

handle

The handle of the new WebWindow.

type

The created type of top-level browsing context.

### Errors

Invalid session ID

Session does not exist.

No such window

If the `window` has been closed.

Unexpected alert open

A user prompt, such as `window.alert`, blocks execution of command until it is dealt with.

Unsupported Operation

The driver or browser doesn't support the command for some reason (e.g., when it is not possible to create a new tab or window).

Example
-------

Specifications
--------------

| Specification |
| --- |
| WebDriver # dfn-new-window |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Close Window command


Set Timeouts - WebDriver

Set Timeouts
============

The *Set Timeouts* command of the WebDriver API sets the timeouts associated with the current session. The session timeout durations control such behavior as timeouts on script injection, document navigation, and element retrieval.

Syntax
------

| Method | URI template |
| --- | --- |
| `POST` | `/session/{session id}/timeouts` |

### URL parameters

`session id`

Identifier of the session.

### Payload

The input is a `Timeouts` object:

`implicit`

Time in milliseconds to retry the element location strategy when finding an element. This defaults to 0, meaning the strategy is run only once.

`pageLoad`

Time in milliseconds to wait for the document to finish loading. By default, WebDriver will wait five minutes (or 300,000 ms).

`script`

Scripts injected with Execute Script or Execute Async Script will run until they hit the script timeout duration, which is also given in milliseconds. The scripts will then be interrupted and a script timeout error will be returned. Defaults to 30 seconds (or 30,000 ms).

### Errors

Invalid session ID

Session does not exist.

Specifications
--------------

| Specification |
| --- |
| WebDriver # dfn-set-timeouts |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Timeouts` object
* List of WebDriver commands


Set Window Rect - WebDriver

Set Window Rect
===============

The *Set Window Rect* command of the WebDriver API alters the size and position of the operating system window associated with the current `window`. The command acts as the setter of Get Window Rect, which return object you can pass directly as this command's payload.

Certain subsets of devices do not support setting the window dimensions or its position. On these configurations the command will return an unsupported operating error. To avoid running into situations where calling this might error it is possible to call it conditionally on whether the `setWindowRect` capability is set to true for the session.

Setting the window rect takes `x`, `y`, `width`, and `height` as input. All the fields are optional, e.g. the command may be called with an empty object, and in this case it will act as a no-op. To set the position both of `x` and `y` are required, and correspondingly both `width` and `height` are required for altering the window's dimensions.

When setting the width or height, it is not guaranteed that the resulting window size will exactly match that which was requested. The driver is expected to clamp values that are larger than the physical screen dimensions, or smaller than the minimum window size. Some drivers may also have other limitations such as not being able to resize in single-pixel increments. For this reason, the returned `width` and `height` might not exactly match `Window.outerWidth` and `Window.outerHeight`.

Setting the window's position is similar in nature to calling `Window.moveTo(x, y)`, but differences itself by bypassing security restrictions related to window manipulation.

The Set Window Rect command is blocking.

Syntax
------

| Method | URI template |
| --- | --- |
| POST | `/session/{session id}/window/rect` |

### URL parameters

`session id`

Identifier of the session.

### Payload

The input is a `WindowRect` object:

`x`

Horizontal position of the `window`, which equivalent to `Window.screenX`. Must be a number in the −(2^31) to 2^31 − 1 range, null, or undefined.

`y`

Vertical position of the `window`, which is equivalent to `Window.screenY`. Must be a number in the −(2^31) to 2^31 − 1 range, null, or undefined.

`width`

Outer width of the `window`, which is equivalent to `Window.outerWidth`. Must be a number in the 0 to 2^31 − 1 range, null, or undefined.

`height`

Outer width of the `window`, which is equivalent to `Window.outerHeight`. Must be a number in the 0 to 2^31 − 1 range, null, or undefined.

### Response

The response payload is a `WindowRect`:

`x`

Horizontal position of the operating system window associated with `window`, equivalent to `Window.screenX`.

`y`

Vertical position of the operating system window associated with `window`, equivalent to `Window.screenY`.

`width`

Width of outer bounds of the operating system window associated with `window`, equivalent to `Window.outerWidth`.

`height`

Height of the outer bounds of the operating system window associated with `window`, equivalent to `Window.outerHeight`.

### Errors

Invalid argument

If any of the fields in the `WindowRect` payload object do not meet the type or bounds constraints, or if only one of the `x`/`y` pair or `width`/`height` pair fields are specified.

Invalid session ID

Session does not exist.

No such window

If the `window` has been closed.

Unexpected alert open

A user prompt, such as `window.alert`, blocks execution of command until it is dealt with.

Unsupported operation

If the driver does not support altering the window's size or position. This is usually the case on mobile devices, where the browser has a set dimension and cannot be moved around on the screen.

You can inspect the `setWindowRect` capability to tell if the device supports this command.

Specifications
--------------

| Specification |
| --- |
| WebDriver # dfn-set-window-rect |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `WebWindow` object
* Associated commands:
    + Get Window Rect
    + Get Window Handle
    + Get Window Handles
    + Close Window


Unknown error - WebDriver

Unknown error
=============

The **unknown element** error is a WebDriver error that occurs when an unspecified error occurs in the driver whilst processing a command.

An unknown error will usually be specific to a particular driver, so it's a good idea to read the error message, if any, for an indication of what happened.

See also
--------

* List of WebDriver errors
* List of WebDriver commands


JavaScript error - WebDriver

JavaScript error
================

The **JavaScript** error is a WebDriver error that occurs when a script the supplied by the user fails to execute.

The underlying cause of the execution error is often supplied in the error message, along with a stacktrace provided by the JavaScript engine in the browser.

Example
-------

Consider the following injected script which tries to use an undefined variable. In JavaScript this normally causes a ReferenceError to be thrown. WebDriver catches this error and serializes it as a JavaScript error:

```python
from selenium import webdriver
from selenium.common import exceptions

session = webdriver.Firefox()
try:
    session.execute_script("return foo")
except exceptions.JavascriptException as e:
    print(e.message)
```

Output:
```

JavascriptException: ReferenceError: foo is not defined
```

See also
--------

* List of WebDriver errors
* Associated commands:
    + Execute Script
    + Execute Async Script


Stale element reference - WebDriver

Stale element reference
=======================

The **stale element reference** error is a WebDriver error that occurs because the referenced web element is no longer attached to the DOM.

 Every DOM element is represented in WebDriver by a unique identifying reference, known as a *web element*.
 The web element reference is a UUID used to execute commands targeting specific elements, such as getting an element's tag name and retrieving a property off an element.

When an element is no longer attached to the DOM, i.e. it has been removed from the document or the document has changed, it is said to be *stale*. Staleness occurs for example when you have a web element reference and the document it was retrieved from navigates.

Examples
--------

### Document navigation

Upon navigation, all web element references to the previous document will be discarded along with the document. This will cause any subsequent interaction with the web element to fail with the stale element reference error:

```python
import urllib

from selenium import webdriver
from selenium.common import exceptions

def inline(doc):
    return "data:text/html;charset=utf-8,{}".format(urllib.quote(doc))

session = webdriver.Firefox()
session.get(inline("<strong>foo</strong>"))
foo = session.find_element_by_css_selector("strong")

session.get(inline("<i>bar</i>"))
try:
    foo.tag_name
except exceptions.StaleElementReferenceException as e:
    print(e)
```

Output:
```

StaleElementReferenceException: The element reference of e75a1764-ff73-40fa-93c1-08cb90394b65 is stale either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
```

### Node removal

When a document node is removed from the DOM, its web element reference will be invalidated. This will also cause any subsequent interaction with the web element to fail with the stale element reference error:

```python
import urllib

from selenium import webdriver
from selenium.common import exceptions

def inline(doc):
    return "data:text/html;charset=utf-8,{}".format(urllib.quote(doc))

session = webdriver.Firefox()
session.get(inline("<button>foo</button>"))
button = session.find_element_by_css_selector("button")
session.execute_script("""
 let [button] = arguments;
 button.remove();
 """, script_args=(button,))

try:
    button.click()
except exceptions.StaleElementReferenceException as e:
    print(e)
```

Output:
```

StaleElementReferenceException: The element reference of e75a1764-ff73-40fa-93c1-08cb90394b65 is stale either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
```

See also
--------

* WebElement
* Associated commands:
    + Find Element
    + Find Elements
    + Find Element From Element
    + Find Elements From Element


Invalid cookie domain - WebDriver

Invalid cookie domain
=====================

The **invalid cookie domain** error is a WebDriver error that occurs when an illegal attempt was made to set a cookie under a different domain than that of the current document.

In WebDriver it is not permissible to set cookies for other domains than the domain of the current browsing context's document's domain.

This error will also happen if the document is *cookie-averse*, that is if the document is not loaded via `http://`, `https://`, or `ftp://`.

Example
-------

### Other domains

If the current domain were to be `example.com`, it would not be possible to add a cookie for the domain `example.org`:

```python
from selenium import webdriver
from selenium.common import exceptions

session = webdriver.Firefox()
session.get("https://example.com/")
try:
    cookie = {"name": "foo",
              "value": "bar",
              "domain": "example.org"}
    session.add_cookie(cookie)
except exceptions.InvalidCookieDomainException as e:
    print(e.message)
```

Output:
```

InvalidCookieDomainException: https://example.org/
```

### Cookie-averse documents

This error may also occur when you visit a cookie-averse document, such as a file on your local disk:

```python
from selenium import webdriver
from selenium.common import exceptions

session = webdriver.Firefox()
session.get("file:///home/jdoe/document.html")
try:
    foo_cookie = {"name": "foo", "value": "bar"}
    session.add_cookie(foo_cookie)
except exceptions.InvalidCookieDomainException as e:
    print(e.message)
```

Output:
```

InvalidCookieDomainException: Document is cookie-averse
```

See also
--------

* List of WebDriver errors
* Relevant WebDriver commands:
    + Add Cookie
    + Delete Cookie
    + Delete All Cookies
    + Get All Cookies
    + Get Named Cookie


Unknown command - WebDriver

Unknown command
===============

The **unknown command** error is a WebDriver error that occurs when the driver does not recognize the command/HTTP endpoint.

Examples
--------

The `/session/{session id}/foo` endpoint does not exist, and will return an unknown command error with a `404 Not Found` HTTP status code:

```bash
curl -i -d '{}' http://localhost:4444/session/foo
```

```http
HTTP/1.1 404 Not Found
Connection: close
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache
Content-Length: 113
Date: Fri, 30 Mar 2018 15:30:51 GMT

{"value":{"error":"unknown command","message":"POST /session/asd did not match a known command","stacktrace":""}}
```

See also
--------

* List of WebDriver errors
* List of WebDriver commands


Invalid selector - WebDriver

Invalid selector
================

The **invalid selector** error is a WebDriver error that occurs when an element retrieval command is used with an unknown web element selector strategy.

The available selector strategies are CSS, link text, partial link text, tag name, and XPath. Any other selector strategy is rejected with this error.

See also
--------

* List of WebDriver errors
* WebElement
* Element retrieval commands:
    + Find Element
    + Find Elements
    + Find Element From Element
    + Find Elements From Element


Script timeout - WebDriver

Script timeout
==============

The **script timeout** error is a WebDriver error that occurs when a script the user has provided did not complete before the session's script timeout duration expired.

The script timeout duration is a configurable capability, which means you can change how long it will take before the driver interrupts an injected script. The driver will by default wait 30 seconds before interrupting the script and returning with a script timeout error, but this can be both extended, limited, and be set to indefinite.

If the session script timeout duration is set to indefinite by using a `null` value, you are at risk of putting the session into a non-recoverable state. Be aware that this should be used with caution.

Example
-------

Consider the following asynchronous script that will resolve the promise, or invoke the callback, after 35 seconds have passed:

```python
from selenium import webdriver
from selenium.common import exceptions

session = webdriver.Firefox()
try:
    session.execute_script("""
 let [resolve] = arguments;
 setTimeout(resolve, 35000);
 """)
except exceptions.ScriptTimeoutException as e:
    print(e.message)
```

Output:
```

ScriptTimeoutException: Timed out after 35000 ms
```

However, it is possible to *extend* the session's default script timeout by using capabilities if you have a script that you expect will take longer:

```python
from selenium import webdriver
from selenium.common import exceptions

session = webdriver.Firefox(capabilities={"alwaysMatch": {"timeouts": {"script": 150000}}})
session.execute_script("""
 let [resolve] = arguments;
 setTimeout(resolve, 35000);
 """)
print("finished successfully")
```

Output:
```

finished successfully
```

See also
--------

* List of WebDriver errors
* Associated commands and types:
    + JavaScript error
    + Execute Script
    + Execute Async Script


Invalid session ID - WebDriver

Invalid session ID
==================

The **invalid session ID** error is a WebDriver error that occurs when the server does not recognize the unique session identifier. This happens if the session has been deleted or if the session ID is invalid.

Example
-------

### Explicit session deletion

A WebDriver session is explicitly deleted when quitting:

```python
from selenium import webdriver
from selenium.common import exceptions

session = webdriver.Firefox()
print("Current session is {}".format(session.session_id))
session.quit()

try:
    session.get("https://mozilla.org")
except exceptions.InvalidSessionIdException as e:
    print(e.message)
```

Output:
```

Current session is 46197c16-8373-469b-bc56-4c4d9e4132b4
No active session with ID 46197c16-8373-469b-bc56-4c4d9e4132b4
```

### Implicit session deletion

The session can also be *implicitly deleted* if you close the last window or tab:

```python
from selenium import webdriver
from selenium.common import exceptions

session = webdriver.Firefox()
print("Current session is {}".format(session.session_id))

# closes current window/tab
session.close()

try:
    session.get("https://mozilla.org")
except exceptions.InvalidSessionIdException as e:
    print(e.message)
```

Output:
```

Current session is 46197c16-8373-469b-bc56-4c4d9e4132b4
No active session with ID 46197c16-8373-469b-bc56-4c4d9e4132b4
```

See also
--------

* List of WebDriver errors
* Session not created
* Related WebDriver commands:
    + New Session
    + Delete Session


Invalid argument - WebDriver

Invalid argument
================

The **invalid argument** error is a WebDriver error that occurs when the arguments passed to a command are either invalid or malformed.

Invalid argument errors can be likened to `TypeError`s in JavaScript, in that they can occur for a great many APIs when the input value is not of the expected type or malformed in some way. See the type- and bounds constraints for each WebDriver command.

Example
-------

It is for example not possible to set a window size to a negative value:

```python
from selenium import webdriver
from selenium.common import exceptions

session = webdriver.Firefox()
try:
    session.set_window_size(-100, 0)
except exceptions.InvalidArgumentException as e:
    print(e.message)
```

Output:
```

InvalidArgumentException: Expected -100 to be >= 0
```

See also
--------

* List of WebDriver errors
* List of WebDriver commands


Unknown method - WebDriver

Unknown method
==============

The **unknown method** error is a WebDriver error that occurs when the driver does not recognize the HTTP request method used for the endpoint.

WebDriver provides a largely REST-ish API and not all endpoints in this API has `GET`, `POST`, and `DELETE` methods. This error occurs when you try to call an endpoint with an HTTP request method it does not support.

Examples
--------

The New Session command provides a `POST` request endpoint which lets you create new WebDriver sessions:

```bash
% curl -d '{}' http://localhost:4444/session
{"sessionId":"d4605710-5a4e-4d64-a52a-778bb0c31e00","value":{"XULappId":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","acceptSslCerts":false,"appBuildId":"20160913030425","browserName":"firefox","browserVersion":"51.0a1","command\_id":1,"platform":"LINUX","platformName":"linux","platformVersion":"4.9.0-1-amd64","processId":17474,"proxy":{},"raisesAccessibilityExceptions":false,"rotatable":false,"specificationLevel":0,"takesElementScreenshot":true,"takesScreenshot":true,"version":"51.0a1"}}
```

It also implements the `DELETE` method for ending a session:

```bash
% curl -X DELETE http://localhost:4444/session/d4605710-5a4e-4d64-a52a-778bb0c31e00
{}
```

But it does not, for example, provide a `GET` method, and this will consequently return an unknown method error:

```bash
% curl http://localhost:4444/session/650f9df3-740e-314c-958d-307e41752fae
{"value":{"error":"unknown command","message":"GET /session/650f9df3-740e-314c-958d-307e41752fae did not match a known command","stacktrace":""}}%
```

See also
--------

* List of WebDriver errors
* List of WebDriver commands


Insecure certificate - WebDriver

Insecure certificate
====================

The **insecure certificate** error is a WebDriver error that occurs when the remotely controlled browser hits a certificate warning of any kind. This is usually the result of navigating to a website with an expired or invalid TLS certificate. Examples of invalid certificates include self-signed, revoked, and cryptographically insecure certificates.

Web browsers prevent and block traffic to domains with broken certificates since the communication with the server would be compromised. It is strongly recommended to fix the certificate situation instead of disabling certificate checks, even in test environments.

WebDriver does offer an `acceptInsecureCerts` capability for disabling certificate checks for the length of the session's duration, but it is important to emphasize that its use is highly discouraged and that using it is widely considered a weakness of the test environment.

Example
-------

This is what will happen when navigating to a domain that has a self-signed TLS certificate using the Python client:

```python
from selenium import webdriver
from selenium.common import exceptions

session = webdriver.Firefox()
try:
    session.get("https://self-signed.badssl.com/")
except exceptions.InsecureCertificateException as e:
    print("Hit insecure cert on {}".format(session.current_url))
```

Output:
```

Hit an insecure cert on https://self-signed.badssl.com/
```

See also
--------

* Navigate To command
* Capabilities
* badssl.com


HTML reference - HTML: HyperText Markup Language

HTML reference
==============

This HTML reference describes all **elements** and **attributes** of HTML, including **global attributes** that apply to all elements.

HTML element reference

This page lists all the HTML elements, which are created using tags.

HTML attribute reference

Elements in HTML have attributes; these are additional values that configure the elements or adjust their behavior in various ways to meet the criteria the users want.

Global attributes

Global attributes are attributes common to all HTML elements; they can be used on all elements, though they may have no effect on some elements.

Content categories

Every HTML element is a member of one or more content categories — these categories group elements that share common characteristics.

Date and time formats used in HTML

Certain HTML elements allow you to specify dates and/or times as the value or as the value of an attribute. These include the date and time variations of the `<input>` element as well as the `<ins>` and `<del>` elements.