How to perform a context click in WebDriver.io Javascript

How to perform a context click in WebDriver.io Javascript

Context clicks are a powerful feature in web applications, allowing users to access additional functionality by right-clicking on an element. In JavaScript and WebDriver.io, context clicks can be achieved using the "performActions" method.

Performing a Context Click

const element = await browser.$("//span[@class='mw-page-title-main' and contains(text(),'Hello, World!')]")
await element.moveTo();
await browser.performActions([
    {
        type: "pointer",
        id: "mouse",
        parameters: { pointerType: "mouse" },
        actions: [
            { type: "pointerMove", origin: element, x: 0, y: 0  },
            { type: "pointerDown", button: 2},
            { type: "pointerUp", button: 2 },
        ],
    },
]);

This code snippet performs a context click on an element with the xpath "//span[@class='mw-page-title-main' and contains(text(),'Hello, World!')]". The "moveTo()" method moves the mouse to the center of the element, and then the "performActions" method simulates the right-click. This will open the context menu for the element, allowing further interactions with it.

Note that the x and y values can be changed if you need to move by a certain offset relative to the targeted element before performing the context click.

Here is an example test that uses the above code snippet.

See Working Example


Leave a reply

Your email address will not be published. Required fields are marked*

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.