From 62cb6958faec0076fd7274bc6dc1489c57996180 Mon Sep 17 00:00:00 2001 From: Steve Dudenhoeffer Date: Mon, 3 Mar 2025 23:31:51 -0500 Subject: [PATCH] Add SetVisible and SetAttribute methods to Node interface This commit introduces two new methods, SetVisible and SetAttribute, to the Node interface. These methods allow toggling element visibility and setting attributes dynamically. Additionally, a helper function, escapeJavaScript, was added to ensure proper escaping of JavaScript strings. --- node.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/node.go b/node.go index ecfba2b..4730f0e 100644 --- a/node.go +++ b/node.go @@ -1,6 +1,9 @@ package extractor import ( + "fmt" + "strings" + "github.com/playwright-community/playwright-go" ) @@ -17,6 +20,9 @@ type Node interface { SelectFirst(selector string) Node ForEach(selector string, fn func(Node) error) error + + SetVisible(val bool) error + SetAttribute(name, value string) error } type node struct { @@ -79,3 +85,17 @@ func (n node) ForEach(selector string, fn func(Node) error) error { return nil } + +func (n node) SetVisible(val bool) error { + _, err := n.locator.Evaluate(fmt.Sprintf(`(element) => element.visible = %t;`, val), nil) + return err +} + +func escapeJavaScript(s string) string { + return strings.Replace(strings.Replace(s, "\\", "\\\\", -1), "'", "\\'", -1) +} + +func (n node) SetAttribute(name, value string) error { + _, err := n.locator.Evaluate(fmt.Sprintf(`(element) => element.setAttribute('%s', '%s');`, escapeJavaScript(name), escapeJavaScript(value)), nil) + return err +}