How to use ElementByJS method of rod Package

Best Rod code snippet using rod.ElementByJS

query.go

Source:query.go Github

copy

Full Screen

...120}121// Element retries until an element in the page that matches the CSS selector, then returns122// the matched element.123func (p *Page) Element(selector string) (*Element, error) {124 return p.ElementByJS(evalHelper(js.Element, selector))125}126// ElementR retries until an element in the page that matches the css selector and it's text matches the jsRegex,127// then returns the matched element.128func (p *Page) ElementR(selector, jsRegex string) (*Element, error) {129 return p.ElementByJS(evalHelper(js.ElementR, selector, jsRegex))130}131// ElementX retries until an element in the page that matches one of the XPath selectors, then returns132// the matched element.133func (p *Page) ElementX(xPath string) (*Element, error) {134 return p.ElementByJS(evalHelper(js.ElementX, xPath))135}136// ElementByJS returns the element from the return value of the js function.137// If sleeper is nil, no retry will be performed.138// By default, it will retry until the js function doesn't return null.139// To customize the retry logic, check the examples of Page.Sleeper.140func (p *Page) ElementByJS(opts *EvalOptions) (*Element, error) {141 var res *proto.RuntimeRemoteObject142 var err error143 removeTrace := func() {}144 err = utils.Retry(p.ctx, p.sleeper(), func() (bool, error) {145 remove := p.tryTraceQuery(opts)146 removeTrace()147 removeTrace = remove148 res, err = p.Evaluate(opts.ByObject())149 if err != nil {150 return true, err151 }152 if res.Type == proto.RuntimeRemoteObjectTypeObject && res.Subtype == proto.RuntimeRemoteObjectSubtypeNull {153 return false, nil154 }155 return true, nil156 })157 removeTrace()158 if err != nil {159 return nil, err160 }161 if res.Subtype != proto.RuntimeRemoteObjectSubtypeNode {162 return nil, &ErrExpectElement{res}163 }164 return p.ElementFromObject(res)165}166// Elements returns all elements that match the css selector167func (p *Page) Elements(selector string) (Elements, error) {168 return p.ElementsByJS(evalHelper(js.Elements, selector))169}170// ElementsX returns all elements that match the XPath selector171func (p *Page) ElementsX(xpath string) (Elements, error) {172 return p.ElementsByJS(evalHelper(js.ElementsX, xpath))173}174// ElementsByJS returns the elements from the return value of the js175func (p *Page) ElementsByJS(opts *EvalOptions) (Elements, error) {176 res, err := p.Evaluate(opts.ByObject())177 if err != nil {178 return nil, err179 }180 if res.Subtype != proto.RuntimeRemoteObjectSubtypeArray {181 return nil, &ErrExpectElements{res}182 }183 defer func() { err = p.Release(res) }()184 list, err := proto.RuntimeGetProperties{185 ObjectID: res.ObjectID,186 OwnProperties: true,187 }.Call(p)188 if err != nil {189 return nil, err190 }191 elemList := Elements{}192 for _, obj := range list.Result {193 if obj.Name == "__proto__" || obj.Name == "length" {194 continue195 }196 val := obj.Value197 if val.Subtype != proto.RuntimeRemoteObjectSubtypeNode {198 return nil, &ErrExpectElements{val}199 }200 el, err := p.ElementFromObject(val)201 if err != nil {202 return nil, err203 }204 elemList = append(elemList, el)205 }206 return elemList, err207}208// Search for the given query in the DOM tree until the result count is not zero, before that it will keep retrying.209// The query can be plain text or css selector or xpath.210// It will search nested iframes and shadow doms too.211func (p *Page) Search(query string) (*SearchResult, error) {212 sr := &SearchResult{213 page: p,214 restore: p.EnableDomain(proto.DOMEnable{}),215 }216 err := utils.Retry(p.ctx, p.sleeper(), func() (bool, error) {217 if sr.DOMPerformSearchResult != nil {218 _ = proto.DOMDiscardSearchResults{SearchID: sr.SearchID}.Call(p)219 }220 res, err := proto.DOMPerformSearch{221 Query: query,222 IncludeUserAgentShadowDOM: true,223 }.Call(p)224 if err != nil {225 return true, err226 }227 sr.DOMPerformSearchResult = res228 if res.ResultCount == 0 {229 return false, nil230 }231 result, err := proto.DOMGetSearchResults{232 SearchID: res.SearchID,233 FromIndex: 0,234 ToIndex: 1,235 }.Call(p)236 if err != nil {237 // when the page is still loading the search result is not ready238 if errors.Is(err, cdp.ErrCtxNotFound) ||239 errors.Is(err, cdp.ErrSearchSessionNotFound) {240 return false, nil241 }242 return true, err243 }244 id := result.NodeIds[0]245 // TODO: This is definitely a bad design of cdp, hope they can optimize it in the future.246 // It's unnecessary to ask the user to explicitly call it.247 //248 // When the id is zero, it means the proto.DOMDocumentUpdated has fired which will249 // invlidate all the existing NodeID. We have to call proto.DOMGetDocument250 // to reset the remote browser's tracker.251 if id == 0 {252 _, _ = proto.DOMGetDocument{}.Call(p)253 return false, nil254 }255 el, err := p.ElementFromNode(&proto.DOMNode{NodeID: id})256 if err != nil {257 return true, err258 }259 sr.First = el260 return true, nil261 })262 if err != nil {263 return nil, err264 }265 return sr, nil266}267// SearchResult handler268type SearchResult struct {269 *proto.DOMPerformSearchResult270 page *Page271 restore func()272 // First element in the search result273 First *Element274}275// Get l elements at the index of i from the remote search result.276func (s *SearchResult) Get(i, l int) (Elements, error) {277 result, err := proto.DOMGetSearchResults{278 SearchID: s.SearchID,279 FromIndex: i,280 ToIndex: i + l,281 }.Call(s.page)282 if err != nil {283 return nil, err284 }285 list := Elements{}286 for _, id := range result.NodeIds {287 el, err := s.page.ElementFromNode(&proto.DOMNode{NodeID: id})288 if err != nil {289 return nil, err290 }291 list = append(list, el)292 }293 return list, nil294}295// All returns all elements296func (s *SearchResult) All() (Elements, error) {297 return s.Get(0, s.ResultCount)298}299// Release the remote search result300func (s *SearchResult) Release() {301 s.restore()302 _ = proto.DOMDiscardSearchResults{SearchID: s.SearchID}.Call(s.page)303}304type raceBranch struct {305 condition func(*Page) (*Element, error)306 callback func(*Element) error307}308// RaceContext stores the branches to race309type RaceContext struct {310 page *Page311 branches []*raceBranch312}313// Race creates a context to race selectors314func (p *Page) Race() *RaceContext {315 return &RaceContext{page: p}316}317// Element the doc is similar to MustElement318func (rc *RaceContext) Element(selector string) *RaceContext {319 rc.branches = append(rc.branches, &raceBranch{320 condition: func(p *Page) (*Element, error) { return p.Element(selector) },321 })322 return rc323}324// ElementX the doc is similar to ElementX325func (rc *RaceContext) ElementX(selector string) *RaceContext {326 rc.branches = append(rc.branches, &raceBranch{327 condition: func(p *Page) (*Element, error) { return p.ElementX(selector) },328 })329 return rc330}331// ElementR the doc is similar to ElementR332func (rc *RaceContext) ElementR(selector, regex string) *RaceContext {333 rc.branches = append(rc.branches, &raceBranch{334 condition: func(p *Page) (*Element, error) { return p.ElementR(selector, regex) },335 })336 return rc337}338// ElementByJS the doc is similar to MustElementByJS339func (rc *RaceContext) ElementByJS(opts *EvalOptions) *RaceContext {340 rc.branches = append(rc.branches, &raceBranch{341 condition: func(p *Page) (*Element, error) { return p.ElementByJS(opts) },342 })343 return rc344}345// Handle adds a callback function to the most recent chained selector.346// The callback function is run, if the corresponding selector is347// present first, in the Race condition.348func (rc *RaceContext) Handle(callback func(*Element) error) *RaceContext {349 rc.branches[len(rc.branches)-1].callback = callback350 return rc351}352// Do the race353func (rc *RaceContext) Do() (*Element, error) {354 var el *Element355 err := utils.Retry(rc.page.ctx, rc.page.sleeper(), func() (stop bool, err error) {356 for _, branch := range rc.branches {357 bEl, err := branch.condition(rc.page.Sleeper(NotFoundSleeper))358 if err == nil {359 el = bEl.Sleeper(rc.page.sleeper)360 if branch.callback != nil {361 err = branch.callback(el)362 }363 return true, err364 } else if !errors.Is(err, &ErrElementNotFound{}) {365 return true, err366 }367 }368 return369 })370 return el, err371}372// Has an element that matches the css selector373func (el *Element) Has(selector string) (bool, *Element, error) {374 el, err := el.Element(selector)375 if errors.Is(err, &ErrElementNotFound{}) {376 return false, nil, nil377 }378 return err == nil, el, err379}380// HasX an element that matches the XPath selector381func (el *Element) HasX(selector string) (bool, *Element, error) {382 el, err := el.ElementX(selector)383 if errors.Is(err, &ErrElementNotFound{}) {384 return false, nil, nil385 }386 return err == nil, el, err387}388// HasR returns true if a child element that matches the css selector and its text matches the jsRegex.389func (el *Element) HasR(selector, jsRegex string) (bool, *Element, error) {390 el, err := el.ElementR(selector, jsRegex)391 if errors.Is(err, &ErrElementNotFound{}) {392 return false, nil, nil393 }394 return err == nil, el, err395}396// Element returns the first child that matches the css selector397func (el *Element) Element(selector string) (*Element, error) {398 return el.ElementByJS(evalHelper(js.Element, selector))399}400// ElementR returns the first child element that matches the css selector and its text matches the jsRegex.401func (el *Element) ElementR(selector, jsRegex string) (*Element, error) {402 return el.ElementByJS(evalHelper(js.ElementR, selector, jsRegex))403}404// ElementX returns the first child that matches the XPath selector405func (el *Element) ElementX(xPath string) (*Element, error) {406 return el.ElementByJS(evalHelper(js.ElementX, xPath))407}408// ElementByJS returns the element from the return value of the js409func (el *Element) ElementByJS(opts *EvalOptions) (*Element, error) {410 e, err := el.page.Sleeper(NotFoundSleeper).ElementByJS(opts.This(el.Object))411 if err != nil {412 return nil, err413 }414 return e.Sleeper(el.sleeper), nil415}416// Parent returns the parent element in the DOM tree417func (el *Element) Parent() (*Element, error) {418 return el.ElementByJS(Eval(`this.parentElement`))419}420// Parents that match the selector421func (el *Element) Parents(selector string) (Elements, error) {422 return el.ElementsByJS(evalHelper(js.Parents, selector))423}424// Next returns the next sibling element in the DOM tree425func (el *Element) Next() (*Element, error) {426 return el.ElementByJS(Eval(`this.nextElementSibling`))427}428// Previous returns the previous sibling element in the DOM tree429func (el *Element) Previous() (*Element, error) {430 return el.ElementByJS(Eval(`this.previousElementSibling`))431}432// Elements returns all elements that match the css selector433func (el *Element) Elements(selector string) (Elements, error) {434 return el.ElementsByJS(evalHelper(js.Elements, selector))435}436// ElementsX returns all elements that match the XPath selector437func (el *Element) ElementsX(xpath string) (Elements, error) {438 return el.ElementsByJS(evalHelper(js.ElementsX, xpath))439}440// ElementsByJS returns the elements from the return value of the js441func (el *Element) ElementsByJS(opts *EvalOptions) (Elements, error) {442 return el.page.Context(el.ctx).ElementsByJS(opts.This(el.Object))443}...

Full Screen

Full Screen

ElementByJS

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().Connect()4 input := page.ElementByJS(`document.querySelector("input[name=q]")`)5 input.Input("rod")6 input.MustPress(proto.InputKeyEnter)7 page.WaitLoad()8 page.MustScreenshot("search-results.png")9}10import (11func main() {12 browser := rod.New().Connect()13 input := page.ElementByJS(`document.querySelector("input[name=q]")`)14 input.Input("rod")15 input.MustPress(proto.InputKeyEnter)16 page.WaitLoad()17 page.MustScreenshot("search-results.png")18}19import (20func main() {21 browser := rod.New().Connect()22 input := page.ElementByJS(`document.querySelector("input[name=q]")`)23 input.Input("rod")24 input.MustPress(proto.InputKeyEnter)25 page.WaitLoad()26 page.MustScreenshot("search-results.png")27}28import (

Full Screen

Full Screen

ElementByJS

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 l := launcher.New().Headless(false)4 defer l.Cleanup()5 browser := rod.New().Client(l.Client()).Connect()6 page.ElementByJS(`() => document.querySelector('input[name="q"]')`).Input("rod")7 page.Keyboard.Press("Enter")8 page.Screenshot("./screenshots/2.png")9 fmt.Println("Screenshot saved successfully")10}11import (12func main() {13 l := launcher.New().Headless(false)14 defer l.Cleanup()15 browser := rod.New().Client(l.Client()).Connect()16 page.ElementByJS(`() => document.querySelector('input[name="q"]')`).Input("rod")17 page.Keyboard.Press("Enter")18 page.Screenshot("./screenshots/3.png")19 fmt.Println("Screenshot saved successfully")20}21import (22func main() {23 l := launcher.New().Headless(false)24 defer l.Cleanup()25 browser := rod.New().Client(l.Client()).Connect()26 page.ElementByJS(`() => document.querySelector('input[name="q"]')`).Input("rod")27 page.Keyboard.Press("Enter")28 page.Screenshot("./screenshots/4.png")29 fmt.Println("Screenshot saved successfully")30}31import (32func main() {33 l := launcher.New().Headless(false)34 defer l.Cleanup()35 browser := rod.New().Client(l.Client()).Connect()36 page.ElementByJS(`() => document.querySelector('input[name="q"]')`).Input("

Full Screen

Full Screen

ElementByJS

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().Connect()4 page.ElementByJS(`document.querySelector("input[name='q']")`, &proto.RuntimeRemoteObject{})5}6import (7func main() {8 browser := rod.New().Connect()9}10import (11func main() {12 browser := rod.New().Connect()13 page.ElementX(`document.querySelector("input[name='q']")`, &proto.RuntimeRemoteObject{})14}15import (16func main() {17 browser := rod.New().Connect()18 page.Elements(`input[name="q"]`, &proto.RuntimeRemoteObject{})19}20import (21func main() {22 browser := rod.New().Connect()23 page.ElementsE(`input[name="q"]`, &proto.RuntimeRemoteObject{})24}25import (26func main() {27 browser := rod.New().Connect()

Full Screen

Full Screen

ElementByJS

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 l := launcher.New().Headless(false).Launch()4 browser := rod.New().ControlURL(l).Connect()5 elem := page.ElementByJS(`() => document.querySelector("input")`)6 elem.Input("rod")7}

Full Screen

Full Screen

ElementByJS

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()4 input := page.MustElementByJS(`document.querySelector("input[name='q']")`)5 fmt.Println(input.MustText())6}7import (8func main() {9 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()10 input := page.MustElementByJS(`document.querySelector("input[name='q']")`)11 fmt.Println(input.MustText())12}13import (14func main() {15 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()16 input := page.MustElementByJS(`document.querySelector("input[name='q']")`)17 fmt.Println(input.MustText())18}19import (20func main() {21 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()22 input := page.MustElementByJS(`document.querySelector("input[name='

Full Screen

Full Screen

ElementByJS

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()4 el := page.MustElementByJS(`document.querySelector("input")`)5 fmt.Println(el)6 time.Sleep(5 * time.Second)7 browser.MustClose()8}9import (10func main() {11 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()12 el := page.MustElementByJSX(`<input />`)13 fmt.Println(el)14 time.Sleep(5 * time.Second)15 browser.MustClose()16}17import (18func main() {19 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()20 el := page.MustElementBySearch(`input`)21 fmt.Println(el)22 time.Sleep(5 * time.Second)23 browser.MustClose()24}

Full Screen

Full Screen

ElementByJS

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 url := launcher.NewUserMode().MustLaunch()4 browser := rod.New().ControlURL(url).MustConnect()5 page.ElementByJS(`document.querySelector("input[title='Search']")`).MustInput("Hello World")6}7import (8func main() {9 url := launcher.NewUserMode().MustLaunch()10 browser := rod.New().ControlURL(url).MustConnect()11 page.ElementByJSX(`<input title="Search">`).MustInput("Hello World")12}13import (14func main() {15 url := launcher.NewUserMode().MustLaunch()16 browser := rod.New().ControlURL(url).MustConnect()17}18import (19func main() {20 url := launcher.NewUserMode().MustLaunch()21 browser := rod.New().ControlURL(url).MustConnect()22 page.ElementBySearch(`input[title

Full Screen

Full Screen

ElementByJS

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()4 element := page.MustElementByJS(`document.querySelector("input")`)5 element = page.MustElement("input")6 element = page.MustElement("#input")7 element = page.MustElement(`[name="input"]`)8 element = page.MustElement(`a:has-text("Google")`)9 element = page.MustElement(`label:has-text("Google")`)10 element = page.MustElement(`button:has-text("Google")`)11 element = page.MustElement(`[placeholder="Google"]`)12 element = page.MustElement(`[title="Google"]`)13 element = page.MustElement(`a:text-matches("Google")`)14 element = page.MustElement(`label:text-matches("Google")`)15 element = page.MustElement(`button:text-matches("Google")`)16 element = page.MustElement(`[placeholder="Google"]`)17 element = page.MustElement(`[title="Google"]`)18 element = page.MustElement(`[value="Google"]`)19 element = page.MustElement(`[value="Google"]`)

Full Screen

Full Screen

ElementByJS

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()4 page.MustElement("input[name=q]").MustInput("rod").MustPress("Enter")5 page.MustWaitLoad()6 page.MustElement("h3").MustClick()7 title := page.MustTitle()8 println(title)9}10import (11func main() {12 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()13 page.MustElement("input[name=q]").MustInput("rod").MustPress("Enter")14 page.MustWaitLoad()15 page.MustElement("h3").MustClick()16 title := page.MustTitle()17 fmt.Println(title)18}19import (20func main() {21 browser := rod.New().ControlURL(launcher.New().MustLaunch()).MustConnect()22 page.MustElement("input[name=q]").MustInput

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Rod automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful