Movatterモバイル変換


[0]ホーム

URL:


Selenium WebDriver JavaScript API
Modules
selenium-webdriver/chrome
selenium-webdriver/chromium
selenium-webdriver/edge
selenium-webdriver/firefox
selenium-webdriver/ie
selenium-webdriver/safari
Classes
Actions
Alert
AlertPromise
ArgumentValue
BaseLogEntry
BaseParameters
BeforeRequestSent
BoxClipRectangle
Browser
BrowsingContext
BrowsingContextInfo
BrowsingContextInspector
BrowsingContextPartitionDescriptor
Build
Builder
By
BytesValue
Capabilities
CaptureScreenshotParameters
ChannelValue
ClientWindowInfo
ClipRectangle
Command
Command
Condition
ConsoleLogEntry
ContinueRequestParameters
ContinueResponseParameters
Cookie
CookieFilter
CreateContextParameters
Credential
DetachedShadowRootError
Device
DriverService
Builder
ElementClickInterceptedError
ElementClipRectangle
ElementNotInteractableError
ElementNotSelectableError
Entry
Environment
EvaluateResultException
EvaluateResultSuccess
ExceptionDetails
Executor
FetchError
FetchTimingInfo
FileDetector
FileDetector
GenericLogEntry
Header
HttpClient
HttpResponse
Index
Initiator
Input
InsecureCertificateError
InvalidArgumentError
InvalidCharacterError
InvalidCookieDomainError
InvalidCoordinatesError
InvalidElementStateError
InvalidSelectorError
JavascriptError
JavascriptLogEntry
Keyboard
Level
LocalValue
Locator
LogManager
Logger
Message
MoveTargetOutOfBoundsError
NavigateResult
NavigationInfo
Network
NetworkInspector
NoSuchAlertError
NoSuchCookieError
NoSuchElementError
NoSuchFrameError
NoSuchSessionError
NoSuchShadowRootError
NoSuchWindowError
PartialCookie
PartitionDescriptor
PartitionKey
Pointer
Preferences
PrintResult
ProvideResponseParameters
RealmInfo
ReferenceValue
RegExpValue
RelativeBy
RemoteValue
Request
RequestData
Response
ResponseData
ResponseStarted
Result
ScriptManager
ScriptTimeoutError
Select
SeleniumServer
SerializationOptions
Server
Session
SessionNotCreatedError
ShadowRoot
ShadowRootPromise
Source
StaleElementReferenceError
Storage
StorageKeyPartitionDescriptor
TimeoutError
UnableToCaptureScreenError
UnableToSetCookieError
UnexpectedAlertOpenError
UnknownCommandError
UnknownMethodError
UnsupportedOperationError
UrlPattern
VirtualAuthenticatorOptions
WebDriver
WebDriverError
WebElement
WebElementCondition
WebElementPromise
Wheel
WindowRealmInfo
Zip
thenableWebDriverProxy
Driver
Options
ServiceBuilder
Driver
Extensions
Options
ServiceBuilder
Driver
Options
ServiceBuilder
AddonFormatError
Channel
Driver
Options
ServiceBuilder
Driver
Options
ServiceBuilder
Driver
Options
ServiceBuilder
Interfaces
Action
Client
Config
Executor
ISelect
IWebDriver
ManualConfig
Options
Cookie
PacConfig
Options
ServiceOptions
SuiteOptions
TargetBrowser
ThenableWebDriver
Timeouts
Global
Atom
Browser
Button
ByHash
Capability
CommandLineFlag
CommandSpec
CommandTransformer
Config
ErrorCode
EvaluateResultType
INTERNAL_COMPUTE_OFFSET_SCRIPT
InterceptPhase
Key
ManualConfig
Name
NonPrimitiveType
Origin
Origin
PacConfig
PageLoadStrategy
Platform
PrimitiveType
Protocol
RealmType
RemoteReferenceType
RemoteType
RequestOptions
ResultOwnership
SameSite
SpecialNumberType
StdIoOptions
THENABLE_DRIVERS
Transport
Type
Type
Type
Type
USER_AGENT
UserPromptHandler
W3C_COMMAND_MAP
ableToSwitchToFrame
addConsoleHandler
alertIsPresent
arraysEqual
binaryPaths
buildPath
buildRequest
builtTargets
check
checkCodePoint
checkLegacyResponse
checkOptions
checkedCall
checkedNodeCall
color
consoleHandler
copy
copyDir
createDriver
delayed
direct
elementIsDisabled
elementIsEnabled
elementIsNotSelected
elementIsNotVisible
elementIsSelected
elementIsVisible
elementLocated
elementTextContains
elementTextIs
elementTextMatches
elementsLocated
encodeError
ensureFileDetectorsAreEnabled
escapeCss
exec
executeCommand
exists
extractId
filter
filterNonW3CCaps
findFreePort
findInPath
formatSpawnArgs
fromWireValue
fullyResolveKeys
fullyResolved
getAddress
getAvailableBrowsers
getBinary
getBinaryPaths
getBrowsersToTestFromEnv
getBrowsingContextInstance
getHostName
getIPAddress
getJavaPath
getLevel
getLogInspectorInstance
getLogger
getLoopbackAddress
getRequestOptions
getStatus
getTestHook
headersToString
ignore
init
installConsoleHandler
isErrorResponse
isFree
isId
isIdle
isObject
isPromise
isRetryableNetworkError
isSelenium3x
legacyTimeout
load
locate
locateWith
manual
map
mkdir
mkdirp
of
pac
pad
parseHttpResponse
path
projectRoot
read
removeConsoleHandler
requireAtom
resolveCommandLineFlags
resolveWaitMessage
rmDir
sendIndex
sendRequest
serialize
setFileDetector
shouldRetryRequest
socks
splitHostAndPort
stalenessOf
start
startSeleniumServer
stat
stop
suite
suite
system
thenFinally
throwDecodedError
titleContains
titleIs
titleMatches
tmpDir
tmpFile
toExecuteAtomCommand
toMap
toWireValue
tryParse
unlink
unzip
url
urlContains
urlIs
urlMatches
waitForServer
waitForUrl
walkDir
whereIs
withTagName
write
On this page

IWebDriver

Structural interface for a WebDriver client.

Methods

actions(optionsopt) → (non-null) {input.Actions}

Creates a new action sequence using this driver. The sequence will not be submitted for execution until Actions.perform() is called.

Parameters:
NameTypeAttributesDescription
optionsObject<optional>

Configuration options for the action sequence (see Actions documentation for details).

Returns:

A new action sequence for this instance.

Type: 
input.Actions

close() → (non-null) {Promise.<void>}

Closes the current window.

Returns:

A promise that will be resolved when this command has completed.

Type: 
Promise.<void>

execute(commandnon-null) → (non-null) {Promise.<T>}

Executes the provided command.Command using this driver's command.Executor.

Parameters:
NameTypeDescription
commandcommand.Command

The command to schedule.

Returns:

A promise that will be resolved with the command result.

Type: 
Promise.<T>

executeAsyncScript(scriptnon-null, …args) → (non-null) {IThenable.<T>}

Executes a snippet of asynchronous JavaScript in the context of the currently selected frame or window. The script fragment will be executed as the body of an anonymous function. If the script is provided as a function object, that function will be converted to a string for injection into the target window.

Any arguments provided in addition to the script will be included as script arguments and may be referenced using thearguments object. Arguments may be a boolean, number, string, orWebElement. Arrays and objects may also be used as script arguments as long as each item adheres to the types previously mentioned.

Unlike executing synchronous JavaScript with #executeScript, scripts executed with this function must explicitly signal they are finished by invoking the provided callback. This callback will always be injected into the executed function as the last argument, and thus may be referenced witharguments[arguments.length - 1]. The following steps will be taken for resolving this functions return value against the first argument to the script's callback function:

  • For a HTML element, the value will resolve to aWebElement
  • Null and undefined return values will resolve to null
  • Booleans, numbers, and strings will resolve as is
  • Functions will resolve to their string representation
  • For arrays and objects, each member item will be converted according to the rules above

Example #1: Performing a sleep that is synchronized with the currently selected window:

var start = new Date().getTime();driver.executeAsyncScript(    'window.setTimeout(arguments[arguments.length - 1], 500);').    then(function() {      console.log(          'Elapsed time: ' + (new Date().getTime() - start) + ' ms');    });

Example #2: Synchronizing a test with an AJAX application:

var button = driver.findElement(By.id('compose-button'));button.click();driver.executeAsyncScript(    'var callback = arguments[arguments.length - 1];' +    'mailClient.getComposeWindowWidget().onload(callback);');driver.switchTo().frame('composeWidget');driver.findElement(By.id('to')).sendKeys('dog@example.com');

Example #3: Injecting a XMLHttpRequest and waiting for the result. In this example, the inject script is specified with a function literal. When using this format, the function is converted to a string for injection, so it should not reference any symbols not defined in the scope of the page under test.

driver.executeAsyncScript(function() {  var callback = arguments[arguments.length - 1];  var xhr = new XMLHttpRequest();  xhr.open("GET", "/resource/data.json", true);  xhr.onreadystatechange = function() {    if (xhr.readyState == 4) {      callback(xhr.responseText);    }  };  xhr.send('');}).then(function(str) {  console.log(JSON.parse(str)['food']);});
Parameters:
NameTypeAttributesDescription
scriptstring |function

The script to execute.

args*<repeatable>

The arguments to pass to the script.

Returns:

A promise that will resolve to the scripts return value.

Type: 
IThenable.<T>

executeScript(scriptnon-null, …args) → (non-null) {IThenable.<T>}

Executes a snippet of JavaScript in the context of the currently selected frame or window. The script fragment will be executed as the body of an anonymous function. If the script is provided as a function object, that function will be converted to a string for injection into the target window.

Any arguments provided in addition to the script will be included as script arguments and may be referenced using thearguments object. Arguments may be a boolean, number, string, orWebElement. Arrays and objects may also be used as script arguments as long as each item adheres to the types previously mentioned.

The script may refer to any variables accessible from the current window. Furthermore, the script will execute in the window's context, thusdocument may be used to refer to the current document. Any local variables will not be available once the script has finished executing, though global variables will persist.

If the script has a return value (i.e. if the script contains a return statement), then the following steps will be taken for resolving this functions return value:

  • For a HTML element, the value will resolve to aWebElement
  • Null and undefined return values will resolve to null
  • Booleans, numbers, and strings will resolve as is
  • Functions will resolve to their string representation
  • For arrays and objects, each member item will be converted according to the rules above
Parameters:
NameTypeAttributesDescription
scriptstring |function

The script to execute.

args*<repeatable>

The arguments to pass to the script.

Returns:

A promise that will resolve to the scripts return value.

Type: 
IThenable.<T>

findElement(locatornon-null) → (non-null) {WebElementPromise}

Locates an element on the page. If the element cannot be found, a error.NoSuchElementError will be returned by the driver.

This function should not be used to test whether an element is present on the page. Rather, you should use #findElements:

driver.findElements(By.id('foo'))    .then(found => console.log('Element found? %s', !!found.length));

The search criteria for an element may be defined using one of the factories in the webdriver.By namespace, or as a short-hand webdriver.By.Hash object. For example, the following two statements are equivalent:

var e1 = driver.findElement(By.id('foo'));var e2 = driver.findElement({id:'foo'});

You may also provide a custom locator function, which takes as input this instance and returns aWebElement, or a promise that will resolve to a WebElement. If the returned promise resolves to an array of WebElements, WebDriver will use the first element. For example, to find the first visible link on a page, you could write:

var link = driver.findElement(firstVisibleLink);function firstVisibleLink(driver) {  var links = driver.findElements(By.tagName('a'));  return promise.filter(links, function(link) {    return link.isDisplayed();  });}
Parameters:
NameTypeDescription
locatorby.By |function

The locator to use.

Returns:

A WebElement that can be used to issue commands against the located element. If the element is not found, the element will be invalidated and all scheduled commands aborted.

Type: 
WebElementPromise

findElements(locatornon-null) → (non-null) {Promise.<!Array.<!WebElement>>}

Search for multiple elements on the page. Refer to the documentation on #findElement(by) for information on element locator strategies.

Parameters:
NameTypeDescription
locatorby.By |function

The locator to use.

Returns:

A promise that will resolve to an array of WebElements.

Type: 
Promise.<!Array.<!WebElement>>

get(url) → (non-null) {Promise.<void>}

Navigates to the given URL.

Parameters:
NameTypeDescription
urlstring

The fully qualified URL to open.

Returns:

A promise that will be resolved when the document has finished loading.

Type: 
Promise.<void>

getAllWindowHandles() → (non-null) {Promise.<!Array.<string>>}

Retrieves a list of all available window handles.

Returns:

A promise that will be resolved with an array of window handles.

Type: 
Promise.<!Array.<string>>

getCapabilities() → (non-null) {Promise.<!Capabilities>}

Returns:

A promise that will resolve with the instance's capabilities.

Type: 
Promise.<!Capabilities>

getCurrentUrl() → (non-null) {Promise.<string>}

Retrieves the URL for the current page.

Returns:

A promise that will be resolved with the current URL.

Type: 
Promise.<string>

getExecutor() → (non-null) {command.Executor}

Returns:

The command executor used by this instance.

Type: 
command.Executor

getPageSource() → (non-null) {Promise.<string>}

Retrieves the current page's source. The returned source is a representation of the underlying DOM: do not expect it to be formatted or escaped in the same way as the raw response sent from the web server.

Returns:

A promise that will be resolved with the current page source.

Type: 
Promise.<string>

getSession() → (non-null) {Promise.<!Session>}

Returns:

A promise for this client's session.

Type: 
Promise.<!Session>

getTitle() → (non-null) {Promise.<string>}

Retrieves the current page title.

Returns:

A promise that will be resolved with the current page's title.

Type: 
Promise.<string>

getWindowHandle() → (non-null) {Promise.<string>}

Retrieves the current window handle.

Returns:

A promise that will be resolved with the current window handle.

Type: 
Promise.<string>

manage() → (non-null) {Options}

Returns:

The options interface for this instance.

Type: 
Options

navigate() → (non-null) {Navigation}

Returns:

The navigation interface for this instance.

Type: 
Navigation

printPage(options)

Takes a PDF of the current page. The driver makes a best effort to return a PDF based on the provided parameters.

Parameters:
NameTypeDescription
optionsObject

quit() → (non-null) {Promise.<void>}

Terminates the browser session. After calling quit, this instance will be invalidated and may no longer be used to issue commands against the browser.

Returns:

A promise that will be resolved when the command has completed.

Type: 
Promise.<void>

setFileDetector(detector)

Sets the file detector that should be used with this instance.

Parameters:
NameTypeDescription
detectorinput.FileDetector

The detector to use ornull.

sleep(ms) → (non-null) {Promise.<void>}

Makes the driver sleep for the given amount of time.

Parameters:
NameTypeDescription
msnumber

The amount of time, in milliseconds, to sleep.

Returns:

A promise that will be resolved when the sleep has finished.

Type: 
Promise.<void>

switchTo() → (non-null) {TargetLocator}

Returns:

The target locator interface for this instance.

Type: 
TargetLocator

takeScreenshot() → (non-null) {Promise.<string>}

Takes a screenshot of the current page. The driver makes the best effort to return a screenshot of the following, in order of preference:

  1. Entire page
  2. Current window
  3. Visible portion of the current frame
  4. The entire display containing the browser
Returns:

A promise that will be resolved to the screenshot as a base-64 encoded PNG.

Type: 
Promise.<string>

wait(conditionnon-null, timeoutopt, messageopt, pollTimeoutopt) → (non-null) {IThenable.<T>|WebElementPromise}

Waits for a condition to evaluate to a "truthy" value. The condition may be specified by aCondition, as a custom function, or as any promise-like thenable.

For aCondition or function, the wait will repeatedly evaluate the condition until it returns a truthy value. If any errors occur while evaluating the condition, they will be allowed to propagate. In the event a condition returns a Promise, the polling loop will wait for it to be resolved and use the resolved value for whether the condition has been satisfied. The resolution time for a promise is always factored into whether a wait has timed out.

If the provided condition is aWebElementCondition, then the wait will return aWebElementPromise that will resolve to the element that satisfied the condition.

Example: waiting up to 10 seconds for an element to be present on the page.

async function example() {  let button =      await driver.wait(until.elementLocated(By.id('foo')), 10000);  await button.click();}
Parameters:
NameTypeAttributesDescription
conditionIThenable.<T> |Condition.<T> |function

The condition to wait on, defined as a promise, condition object, or a function to evaluate as a condition.

timeoutnumber<optional>

The duration in milliseconds, how long to wait for the condition to be true.

messagestring |function<optional>

An optional message to use if the wait times out.

pollTimeoutnumber<optional>

The duration in milliseconds, how long to wait between polling the condition.

Throws:

if the providedcondition is not a valid type.

Type
TypeError
Returns:

A promise that will be resolved with the first truthy value returned by the condition function, or rejected if the condition times out. If the input condition is an instance of aWebElementCondition, the returned value will be aWebElementPromise.

Type: 
IThenable.<T> |WebElementPromise
Type anything to view search result
Selenium WebDriver JavaScript API
GitHub
npm
Modules
selenium-webdriver/chrome
selenium-webdriver/chromium
selenium-webdriver/edge
selenium-webdriver/firefox
selenium-webdriver/ie
selenium-webdriver/safari
Classes
Actions
Alert
AlertPromise
ArgumentValue
BaseLogEntry
BaseParameters
BeforeRequestSent
BoxClipRectangle
Browser
BrowsingContext
BrowsingContextInfo
BrowsingContextInspector
BrowsingContextPartitionDescriptor
Build
Builder
By
BytesValue
Capabilities
CaptureScreenshotParameters
ChannelValue
ClientWindowInfo
ClipRectangle
Command
Command
Condition
ConsoleLogEntry
ContinueRequestParameters
ContinueResponseParameters
Cookie
CookieFilter
CreateContextParameters
Credential
DetachedShadowRootError
Device
DriverService
Builder
ElementClickInterceptedError
ElementClipRectangle
ElementNotInteractableError
ElementNotSelectableError
Entry
Environment
EvaluateResultException
EvaluateResultSuccess
ExceptionDetails
Executor
FetchError
FetchTimingInfo
FileDetector
FileDetector
GenericLogEntry
Header
HttpClient
HttpResponse
Index
Initiator
Input
InsecureCertificateError
InvalidArgumentError
InvalidCharacterError
InvalidCookieDomainError
InvalidCoordinatesError
InvalidElementStateError
InvalidSelectorError
JavascriptError
JavascriptLogEntry
Keyboard
Level
LocalValue
Locator
LogManager
Logger
Message
MoveTargetOutOfBoundsError
NavigateResult
NavigationInfo
Network
NetworkInspector
NoSuchAlertError
NoSuchCookieError
NoSuchElementError
NoSuchFrameError
NoSuchSessionError
NoSuchShadowRootError
NoSuchWindowError
PartialCookie
PartitionDescriptor
PartitionKey
Pointer
Preferences
PrintResult
ProvideResponseParameters
RealmInfo
ReferenceValue
RegExpValue
RelativeBy
RemoteValue
Request
RequestData
Response
ResponseData
ResponseStarted
Result
ScriptManager
ScriptTimeoutError
Select
SeleniumServer
SerializationOptions
Server
Session
SessionNotCreatedError
ShadowRoot
ShadowRootPromise
Source
StaleElementReferenceError
Storage
StorageKeyPartitionDescriptor
TimeoutError
UnableToCaptureScreenError
UnableToSetCookieError
UnexpectedAlertOpenError
UnknownCommandError
UnknownMethodError
UnsupportedOperationError
UrlPattern
VirtualAuthenticatorOptions
WebDriver
WebDriverError
WebElement
WebElementCondition
WebElementPromise
Wheel
WindowRealmInfo
Zip
thenableWebDriverProxy
Driver
Options
ServiceBuilder
Driver
Extensions
Options
ServiceBuilder
Driver
Options
ServiceBuilder
AddonFormatError
Channel
Driver
Options
ServiceBuilder
Driver
Options
ServiceBuilder
Driver
Options
ServiceBuilder
Interfaces
Action
Client
Config
Executor
ISelect
IWebDriver
ManualConfig
Options
Cookie
PacConfig
Options
ServiceOptions
SuiteOptions
TargetBrowser
ThenableWebDriver
Timeouts
Global
Atom
Browser
Button
ByHash
Capability
CommandLineFlag
CommandSpec
CommandTransformer
Config
ErrorCode
EvaluateResultType
INTERNAL_COMPUTE_OFFSET_SCRIPT
InterceptPhase
Key
ManualConfig
Name
NonPrimitiveType
Origin
Origin
PacConfig
PageLoadStrategy
Platform
PrimitiveType
Protocol
RealmType
RemoteReferenceType
RemoteType
RequestOptions
ResultOwnership
SameSite
SpecialNumberType
StdIoOptions
THENABLE_DRIVERS
Transport
Type
Type
Type
Type
USER_AGENT
UserPromptHandler
W3C_COMMAND_MAP
ableToSwitchToFrame
addConsoleHandler
alertIsPresent
arraysEqual
binaryPaths
buildPath
buildRequest
builtTargets
check
checkCodePoint
checkLegacyResponse
checkOptions
checkedCall
checkedNodeCall
color
consoleHandler
copy
copyDir
createDriver
delayed
direct
elementIsDisabled
elementIsEnabled
elementIsNotSelected
elementIsNotVisible
elementIsSelected
elementIsVisible
elementLocated
elementTextContains
elementTextIs
elementTextMatches
elementsLocated
encodeError
ensureFileDetectorsAreEnabled
escapeCss
exec
executeCommand
exists
extractId
filter
filterNonW3CCaps
findFreePort
findInPath
formatSpawnArgs
fromWireValue
fullyResolveKeys
fullyResolved
getAddress
getAvailableBrowsers
getBinary
getBinaryPaths
getBrowsersToTestFromEnv
getBrowsingContextInstance
getHostName
getIPAddress
getJavaPath
getLevel
getLogInspectorInstance
getLogger
getLoopbackAddress
getRequestOptions
getStatus
getTestHook
headersToString
ignore
init
installConsoleHandler
isErrorResponse
isFree
isId
isIdle
isObject
isPromise
isRetryableNetworkError
isSelenium3x
legacyTimeout
load
locate
locateWith
manual
map
mkdir
mkdirp
of
pac
pad
parseHttpResponse
path
projectRoot
read
removeConsoleHandler
requireAtom
resolveCommandLineFlags
resolveWaitMessage
rmDir
sendIndex
sendRequest
serialize
setFileDetector
shouldRetryRequest
socks
splitHostAndPort
stalenessOf
start
startSeleniumServer
stat
stop
suite
suite
system
thenFinally
throwDecodedError
titleContains
titleIs
titleMatches
tmpDir
tmpFile
toExecuteAtomCommand
toMap
toWireValue
tryParse
unlink
unzip
url
urlContains
urlIs
urlMatches
waitForServer
waitForUrl
walkDir
whereIs
withTagName
write

[8]ページ先頭

©2009-2025 Movatter.jp