Wednesday 15 March 2023

Playwright: blur the matching element

Locator.blur() method blur the given element.

 

Signature

void blur()
void blur(BlurOptions options)

 

Example

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

 

Find the below working application.

 

blurAction.html
<!DOCTYPE html>
<html>

<body>
	<h1>Blur action demo</h1>

	Enter something: <input type="text" id="myData" onblur="toUpper()">

	<p>When the input field is blurred or out of scope, 'toUpper' function is triggered which transforms the input text
		to upper case.</p>

	<script>
		function toUpper() {
			let x = document.getElementById("myData");
			x.value = x.value.toUpperCase();
		}
	</script>

</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();
		}

	}
}

BlurAction.java

package com.sample.app.actions;

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 BlurAction {

	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 + "blurAction.html");

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

			page.locator("#myData").type("Hello world!!!!");
			page.locator("#myData").blur();
			String textContent = page.locator("#myData").inputValue();

			System.out.println(textContent);

		}
	}

}

Output

HELLO WORLD!!!!


Previous                                                 Next                                                 Home

No comments:

Post a Comment