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.
This commit is contained in:
Steve Dudenhoeffer 2025-03-03 23:31:51 -05:00
parent 964a98a5a8
commit 62cb6958fa

20
node.go
View File

@ -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
}