Best Rod code snippet using rod.initEvents
browser.go
Source:browser.go
...127 return err128 }129 b.client = c130 }131 b.initEvents()132 if b.monitor != "" {133 launcher.Open(b.ServeMonitor(b.monitor))134 }135 return proto.TargetSetDiscoverTargets{Discover: true}.Call(b)136}137// Close å
³éæµè§å¨138func (b *Browser) Close() error {139 if b.BrowserContextID == "" {140 return proto.BrowserClose{}.Call(b)141 }142 return proto.TargetDisposeBrowserContext{BrowserContextID: b.BrowserContextID}.Call(b)143}144// Page å建ä¸ä¸ªæ°çæµè§å¨æ ç¾ãå¦æopts.URL为空ï¼é»è®¤å¼å°æ¯ "about:blank"ã145func (b *Browser) Page(opts proto.TargetCreateTarget) (p *Page, err error) {146 req := opts147 req.BrowserContextID = b.BrowserContextID148 req.URL = "about:blank"149 target, err := req.Call(b)150 if err != nil {151 return nil, err152 }153 defer func() {154 // å¦æNavigateæPageFromTarget失败ï¼æ们åºè¯¥å
³éç®æ 以é²æ¢æ³æ¼155 if err != nil {156 _, _ = proto.TargetCloseTarget{TargetID: target.TargetID}.Call(b)157 }158 }()159 p, err = b.PageFromTarget(target.TargetID)160 if err != nil {161 return162 }163 if opts.URL == "" {164 return165 }166 err = p.Navigate(opts.URL)167 return168}169// Pages æ£ç´¢ææå¯è§é¡µé¢170func (b *Browser) Pages() (Pages, error) {171 list, err := proto.TargetGetTargets{}.Call(b)172 if err != nil {173 return nil, err174 }175 pageList := Pages{}176 for _, target := range list.TargetInfos {177 if target.Type != proto.TargetTargetInfoTypePage {178 continue179 }180 page, err := b.PageFromTarget(target.TargetID)181 if err != nil {182 return nil, err183 }184 pageList = append(pageList, page)185 }186 return pageList, nil187}188// Call ç¨äºç´æ¥è°ç¨åå§cdpæ¥å£189func (b *Browser) Call(ctx context.Context, sessionID, methodName string, params interface{}) (res []byte, err error) {190 res, err = b.client.Call(ctx, sessionID, methodName, params)191 if err != nil {192 return nil, err193 }194 b.set(proto.TargetSessionID(sessionID), methodName, params)195 return196}197// PageFromSession ç¨äºåºå±è°è¯198func (b *Browser) PageFromSession(sessionID proto.TargetSessionID) *Page {199 sessionCtx, cancel := context.WithCancel(b.ctx)200 return &Page{201 e: b.e,202 ctx: sessionCtx,203 sessionCancel: cancel,204 sleeper: b.sleeper,205 browser: b,206 SessionID: sessionID,207 }208}209// PageFromTarget è·åæå建ä¸ä¸ªPageå®ä¾ã210func (b *Browser) PageFromTarget(targetID proto.TargetTargetID) (*Page, error) {211 b.targetsLock.Lock()212 defer b.targetsLock.Unlock()213 page := b.loadCachedPage(targetID)214 if page != nil {215 return page, nil216 }217 session, err := proto.TargetAttachToTarget{218 TargetID: targetID,219 Flatten: true, // å¦æ没æ设置ï¼å°ä¸è¿åä»»ä½ååºã220 }.Call(b)221 if err != nil {222 return nil, err223 }224 sessionCtx, cancel := context.WithCancel(b.ctx)225 page = &Page{226 e: b.e,227 ctx: sessionCtx,228 sessionCancel: cancel,229 sleeper: b.sleeper,230 browser: b,231 TargetID: targetID,232 SessionID: session.SessionID,233 FrameID: proto.PageFrameID(targetID),234 jsCtxLock: &sync.Mutex{},235 jsCtxID: new(proto.RuntimeRemoteObjectID),236 helpersLock: &sync.Mutex{},237 }238 page.root = page239 page.newKeyboard().newMouse().newTouch()240 if !b.defaultDevice.IsClear() {241 err = page.Emulate(b.defaultDevice)242 if err != nil {243 return nil, err244 }245 }246 b.cachePage(page)247 page.initEvents()248 // å¦ææ们ä¸å¯ç¨å®ï¼å°±ä¼é æå¾å¤ææ³ä¸å°çæµè§å¨è¡ä¸ºã249 // å¦proto.PageAddScriptToEvaluateOnNewDocumentå°±ä¸è½å·¥ä½ã250 page.EnableDomain(&proto.PageEnable{})251 return page, nil252}253// EachEventä¸Page.EachEvent类似ï¼ä½å¯ä»¥æè·æ´ä¸ªæµè§å¨çäºä»¶ã254func (b *Browser) EachEvent(callbacks ...interface{}) (wait func()) {255 return b.eachEvent("", callbacks...)256}257// WaitEvent çå¾
ä¸ä¸ä¸ªäºä»¶çåçï¼æ¶é´ä¸ºä¸æ¬¡ãå®ä¹ä¼å°æ°æ®å è½½å°äºä»¶å¯¹è±¡ä¸ã258func (b *Browser) WaitEvent(e proto.Event) (wait func()) {259 return b.waitEvent("", e)260}261// çå¾
ä¸ä¸ä¸ªäºä»¶çåçï¼çå¾
ä¸æ¬¡ãå®ä¹ä¼å°æ°æ®å è½½å°äºä»¶å¯¹è±¡ä¸ã262func (b *Browser) waitEvent(sessionID proto.TargetSessionID, e proto.Event) (wait func()) {263 valE := reflect.ValueOf(e)264 valTrue := reflect.ValueOf(true)265 if valE.Kind() != reflect.Ptr {266 valE = reflect.New(valE.Type())267 }268 // å¨è¿è¡æ¶å¨æå°å建ä¸ä¸ªå½æ°:269 //270 // func(ee proto.Event) bool {271 // *e = *ee272 // return true273 // }274 fnType := reflect.FuncOf([]reflect.Type{valE.Type()}, []reflect.Type{valTrue.Type()}, false)275 fnVal := reflect.MakeFunc(fnType, func(args []reflect.Value) []reflect.Value {276 valE.Elem().Set(args[0].Elem())277 return []reflect.Value{valTrue}278 })279 return b.eachEvent(sessionID, fnVal.Interface())280}281// å¦æä»»ä½åè°è¿åtrueï¼äºä»¶å¾ªç¯å°åæ¢ã282// å¦æ没æå¯ç¨ç¸å
³çdomainï¼å®å°å¯ç¨ç¸domainï¼å¹¶å¨çå¾
ç»æåæ¢å¤è¿äºdomainã283func (b *Browser) eachEvent(sessionID proto.TargetSessionID, callbacks ...interface{}) (wait func()) {284 cbMap := map[string]reflect.Value{}285 restores := []func(){}286 for _, cb := range callbacks {287 cbVal := reflect.ValueOf(cb)288 eType := cbVal.Type().In(0)289 name := reflect.New(eType.Elem()).Interface().(proto.Event).ProtoEvent()290 cbMap[name] = cbVal291 // åªæå¯ç¨çdomainæä¼åcdp客æ·ç«¯ååºäºä»¶ã292 // å¦æ没æå¯ç¨ç¸å
³domainï¼æ们就为äºä»¶ç±»åå¯ç¨domainã293 // å¨çå¾
ç»æåï¼æ们å°domainæ¢å¤å°å®ä»¬ä¹åçç¶æã294 domain, _ := proto.ParseMethodName(name)295 if req := proto.GetType(domain + ".enable"); req != nil {296 enable := reflect.New(req).Interface().(proto.Request)297 restores = append(restores, b.EnableDomain(sessionID, enable))298 }299 }300 b, cancel := b.WithCancel()301 messages := b.Event()302 return func() {303 if messages == nil {304 panic("can't use wait function twice")305 }306 defer func() {307 cancel()308 messages = nil309 for _, restore := range restores {310 restore()311 }312 }()313 for msg := range messages {314 if !(sessionID == "" || msg.SessionID == sessionID) {315 continue316 }317 if cbVal, has := cbMap[msg.Method]; has {318 e := reflect.New(proto.GetType(msg.Method))319 msg.Load(e.Interface().(proto.Event))320 args := []reflect.Value{e}321 if cbVal.Type().NumIn() == 2 {322 args = append(args, reflect.ValueOf(msg.SessionID))323 }324 res := cbVal.Call(args)325 if len(res) > 0 {326 if res[0].Bool() {327 return328 }329 }330 }331 }332 }333}334// Event æµè§å¨äºä»¶335func (b *Browser) Event() <-chan *Message {336 src := b.event.Subscribe(b.ctx)337 dst := make(chan *Message)338 go func() {339 defer close(dst)340 for {341 select {342 case <-b.ctx.Done():343 return344 case e, ok := <-src:345 if !ok {346 return347 }348 select {349 case <-b.ctx.Done():350 return351 case dst <- e.(*Message):352 }353 }354 }355 }()356 return dst357}358func (b *Browser) initEvents() {359 ctx, cancel := context.WithCancel(b.ctx)360 b.event = goob.New(ctx)361 event := b.client.Event()362 go func() {363 defer cancel()364 for e := range event {365 b.event.Publish(&Message{366 SessionID: proto.TargetSessionID(e.SessionID),367 Method: e.Method,368 lock: &sync.Mutex{},369 data: e.Params,370 })371 }372 }()...
hijack.go
Source:hijack.go
...12 "github.com/ysmood/gson"13)14// HijackRequests same as Page.HijackRequests, but can intercept requests of the entire browser.15func (b *Browser) HijackRequests() *HijackRouter {16 return newHijackRouter(b, b).initEvents()17}18// HijackRequests creates a new router instance for requests hijacking.19// When use Fetch domain outside the router should be stopped. Enabling hijacking disables page caching,20// but such as 304 Not Modified will still work as expected.21// The entire process of hijacking one request:22// browser --req-> rod ---> server ---> rod --res-> browser23// The --req-> and --res-> are the parts that can be modified.24func (p *Page) HijackRequests() *HijackRouter {25 return newHijackRouter(p.browser, p).initEvents()26}27// HijackRouter context28type HijackRouter struct {29 run func()30 stop func()31 handlers []*hijackHandler32 enable *proto.FetchEnable33 client proto.Client34 browser *Browser35}36func newHijackRouter(browser *Browser, client proto.Client) *HijackRouter {37 return &HijackRouter{38 enable: &proto.FetchEnable{},39 browser: browser,40 client: client,41 handlers: []*hijackHandler{},42 }43}44func (r *HijackRouter) initEvents() *HijackRouter {45 ctx := r.browser.ctx46 if cta, ok := r.client.(proto.Contextable); ok {47 ctx = cta.GetContext()48 }49 var sessionID proto.TargetSessionID50 if tsa, ok := r.client.(proto.Sessionable); ok {51 sessionID = tsa.GetSessionID()52 }53 eventCtx, cancel := context.WithCancel(ctx)54 r.stop = cancel55 _ = r.enable.Call(r.client)56 r.run = r.browser.Context(eventCtx).eachEvent(sessionID, func(e *proto.FetchRequestPaused) bool {57 go func() {58 ctx := r.new(eventCtx, e)...
initEvents
Using AI Code Generation
1import (2func main() {3 browser := rod.New().MustConnect()4 page.MustElement("input").MustInput("rod")5 page.MustElement("form").MustSubmit()6 page.MustWaitLoad()7 page.MustScreenshot("screenshot.png")8 page.MustInitEvents()9 page.MustListen(proto.NetworkResponseReceived, func(e *proto.NetworkResponseReceived) {10 fmt.Println(e.Response.Status)11 })12}
initEvents
Using AI Code Generation
1import (2func main() {3 l := launcher.New().Headless(false)4 defer l.Cleanup()5 browser := rod.New().ControlURL(l).MustConnect()6 page.MustElement(`input[name="q"]`).MustInput("rod")7 events := page.MustElement(`input[name="q"]`).MustInitEvents()
initEvents
Using AI Code Generation
1import (2func main() {3 page.MustElement("input[name=q]").MustInput("rod").MustPress(input.Enter)4 fmt.Println(page.MustElement("h3").MustText())5}6import (7func main() {8 page.MustElement("input[name=q]").MustInput("rod").MustPress(input.Enter)9 fmt.Println(page.MustElement("h3").MustText())10}11import (12func main() {13 page.MustElement("input[name=q]").MustInput("rod").MustPress(input.Enter)14 fmt.Println(page.MustElement("h3").MustText())15}16import (17func main() {18 page.MustElement("input[name=q]").MustInput("rod").MustPress(input.Enter)19 fmt.Println(page.MustElement("h3").MustText())20}21import (22func main() {23 page.MustElement("input[name=q]").MustInput("rod").MustPress(input.Enter)24 fmt.Println(page.MustElement("h3").MustText())25}26import (27func main() {28 page.MustElement("input[name=q]").MustInput("rod").MustPress(input.Enter)
initEvents
Using AI Code Generation
1import (2func main() {3 browser := rod.New().MustConnect()4 page.MustInitEvents()5 page.MustWaitLoad()6 fmt.Println(page.MustTitle())7}
initEvents
Using AI Code Generation
1import "fmt"2func main() {3 rod := rod{}4 rod.initEvents()5 fmt.Println(rod)6}7import "fmt"8func main() {9 rod := rod{}10 rod.initEvents()11 fmt.Println(rod)12}13import "fmt"14func main() {15 rod := rod{}16 rod.initEvents()17 fmt.Println(rod)18}19import "fmt"20func main() {21 rod := rod{}22 rod.initEvents()23 fmt.Println(rod)24}25import "fmt"26func main() {27 rod := rod{}28 rod.initEvents()29 fmt.Println(rod)30}31import "fmt"32func main() {33 rod := rod{}34 rod.initEvents()35 fmt.Println(rod)36}37import "fmt"38func main() {39 rod := rod{}40 rod.initEvents()41 fmt.Println(rod)42}43import "fmt"44func main() {45 rod := rod{}46 rod.initEvents()47 fmt.Println(rod)48}49import "fmt"50func main() {51 rod := rod{}52 rod.initEvents()53 fmt.Println(rod)54}55import "fmt"56func main() {57 rod := rod{}58 rod.initEvents()59 fmt.Println(rod)60}61import "fmt"62func main() {63 rod := rod{}64 rod.initEvents()65 fmt.Println(rod)66}
initEvents
Using AI Code Generation
1import "fmt"2func main() {3 var rod = Rod{}4 rod.initEvents()5 rod.printEvents()6}7import "fmt"8func main() {9 var rod = Rod{}10 rod.initEvents()11 rod.printEvents()12}13import "fmt"14func main() {15 var rod = Rod{}16 rod.initEvents()17 rod.printEvents()18}19import "fmt"20func main() {21 var rod = Rod{}22 rod.initEvents()23 rod.printEvents()24}25import "fmt"26func main() {27 var rod = Rod{}28 rod.initEvents()29 rod.printEvents()30}31import "fmt"32func main() {33 var rod = Rod{}34 rod.initEvents()35 rod.printEvents()36}37import "fmt"38func main() {39 var rod = Rod{}40 rod.initEvents()41 rod.printEvents()42}43import "fmt"44func main() {45 var rod = Rod{}46 rod.initEvents()47 rod.printEvents()48}49import "fmt"50func main() {51 var rod = Rod{}52 rod.initEvents()53 rod.printEvents()54}55import "fmt"56func main() {57 var rod = Rod{}58 rod.initEvents()59 rod.printEvents()60}61import "fmt"62func main() {63 var rod = Rod{}64 rod.initEvents()65 rod.printEvents()66}
initEvents
Using AI Code Generation
1import (2func main() {3 ro := rod.NewRod()4 ro.InitEvents()5 fmt.Println(ro.Events)6}7import (8func main() {9 ro := rod.NewRod()10 ro.InitEvents()11 fmt.Println(ro.Events)12}13import (14func main() {15 ro := rod.NewRod()16 ro.InitEvents()17 fmt.Println(ro.Events)18}19import (20func main() {21 ro := rod.NewRod()22 ro.InitEvents()23 fmt.Println(ro.Events)24}25import (26func main() {27 ro := rod.NewRod()28 ro.InitEvents()29 fmt.Println(ro.Events)30}31import (32func main() {33 ro := rod.NewRod()34 ro.InitEvents()35 fmt.Println(ro.Events)36}37import (38func main() {39 ro := rod.NewRod()40 ro.InitEvents()41 fmt.Println(ro.Events)42}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!