Friday 17 March 2023

Playwright: clear the input element

Using Locator.clear() method, we can clear the content of selected input, textarea, or contenteditable elements.

 

Signature

void clear() 
void clear(ClearOptions options)

 

Example

page.locator("#myData").clear();

 

Find the below working application.

 

clearInput.html
<!DOCTYPE html>
<html>

<body>
	<h1>Clear action demo</h1>

	Enter something: <input type="text" id="myData">

</body>

</html>

 

FileUtil.java

package com.sample.app.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class FileUtil {

	public static String resourceAsString(String resourceName) throws IOException {
		ClassLoader classLoader = FileUtil.class.getClassLoader();
		URL url = classLoader.getResource(resourceName);
		if (url == null) {
			return null;
		}

		URLConnection urlConnection = url.openConnection();

		urlConnection.setUseCaches(false);

		try (InputStreamReader inputStreamReader = new InputStreamReader(urlConnection.getInputStream())) {
			char[] buffer = new char[1048];
			StringBuilder builder = new StringBuilder();

			int count = -1;
			while ((count = inputStreamReader.read(buffer, 0, buffer.length)) != -1) {
				builder.append(buffer, 0, count);
			}

			return builder.toString();
		}

	}
}

 

ClearTheData.java

package com.sample.app.locators;

import java.io.File;
import java.io.IOException;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.sample.app.util.FileUtil;

public class ClearTheData {

	public static void main(String[] args) throws IOException, InterruptedException {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium()
					.launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));
			final String content = FileUtil.resourceAsString("actions" + File.separator + "clearInput.html");

			Page page = browser.newPage();
			page.setContent(content);

			System.out.println("Typing the text 'Hello world!!!!'");
			page.locator("#myData").type("Hello world!!!!");
			String textContent = page.locator("#myData").inputValue();
			System.out.println("textContent : '" + textContent + "'");

			System.out.println("\nClearing the text");
			page.locator("#myData").clear();
			textContent = page.locator("#myData").inputValue();
			System.out.println("textContent : '" + textContent + "'");
		}
	}

}

 

Output

Typing the text 'Hello world!!!!'
textContent : 'Hello world!!!!'

Clearing the text
textContent : ''

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment