GithubHelp home page GithubHelp logo

Comments (5)

github-actions avatar github-actions commented on June 21, 2024

Please add a valid Rod Version: v0.0.0 to your issue. Current version is v0.115.0

generated by check-issue

from rod.

sxmxta avatar sxmxta commented on June 21, 2024

Try using browser Connect () initializes InitEvents, but it blocks the UI thread.

There won't be any problem with InitEvents directly

from rod.

ysmood avatar ysmood commented on June 21, 2024

How about use the cdp directly? Look at the code client.Event():

func ExampleClient() {
ctx := context.Background()
// launch a browser
url := launcher.New().MustLaunch()
// create a controller
client := cdp.New().Start(cdp.MustConnectWS(url))
go func() {
for range client.Event() {
// you must consume the events
utils.Noop()
}
}()
// Such as call this endpoint on the api doc:
// https://chromedevtools.github.io/devtools-protocol/tot/Page#method-navigate
// This will create a new tab and navigate to the test.com
res, err := client.Call(ctx, "", "Target.createTarget", map[string]string{
"url": "http://test.com",
})
utils.E(err)
fmt.Println(len(gson.New(res).Get("targetId").Str()))
// close browser by using the proto lib to encode json
_ = proto.BrowserClose{}.Call(client)
// Output: 32
}

from rod.

sxmxta avatar sxmxta commented on June 21, 2024

How about use the cdp directly? Look at the code client.Event():

func ExampleClient() {
ctx := context.Background()
// launch a browser
url := launcher.New().MustLaunch()
// create a controller
client := cdp.New().Start(cdp.MustConnectWS(url))
go func() {
for range client.Event() {
// you must consume the events
utils.Noop()
}
}()
// Such as call this endpoint on the api doc:
// https://chromedevtools.github.io/devtools-protocol/tot/Page#method-navigate
// This will create a new tab and navigate to the test.com
res, err := client.Call(ctx, "", "Target.createTarget", map[string]string{
"url": "http://test.com",
})
utils.E(err)
fmt.Println(len(gson.New(res).Get("targetId").Str()))
// close browser by using the proto lib to encode json
_ = proto.BrowserClose{}.Call(client)
// Output: 32
}

Hello, this method is not suitable.
I have switched to another method, using "go Browser.Connect()" instead of initEvents().

Because it directly passes a []byte, I need to know the id and method, and I don't want to deserialize again to obtain them. I am using the Chromium().ExecuteDevToolsMethod(messageId int32, method string, dictionaryValue *ICefDictionaryValue) function,
so I have replaced it with "go Browser.Connect()". Let's try this approach for now.

func (m *Energy) CreateBrowser() {
	if !m.created {
		m.created = true
		go m.rodBrowser.Connect()
		//m.rodBrowser.InitEvents()
		if m.window != nil {
			// window
			if m.window.IsLCL() {
				cef.RunOnMainThread(func() {
					m.window.Show()
				})
			} else {
				m.window.Show()
			}
		} else if m.chromiumBrowser != nil {
			m.chromiumBrowser.CreateBrowser()
		}
	}
}


// Call a method and wait for its response.
func (m *Energy) Call(ctx context.Context, sessionID, method string, params interface{}) ([]byte, error) {
	req := &cdp.Request{
		ID:        int(atomic.AddUint64(&m.count, 1)),
		SessionID: sessionID,
		Method:    method,
		Params:    params,
	}
	m.logger.Println(req)
	data, err := json.Marshal(params)
	utils.E(err)
	done := make(chan Result)
	once := sync.Once{}
	m.pending.Store(req.ID, func(res Result) {
		once.Do(func() {
			select {
			case <-ctx.Done():
			case done <- res:
			}
		})
	})
	defer m.pending.Delete(req.ID)
	//m.logger.Println("send-data:", string(data))
	//m.chromium.SendDevToolsMessage(string(data))// Linux cannot be used
	dict := JSONParse(data)
	m.ChromiumBrowser().Chromium().ExecuteDevToolsMethod(int32(req.ID), req.Method, dict)
	defer dict.Free()
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	case res := <-done:
		return res.Msg, res.Err
	}
}

from rod.

ysmood avatar ysmood commented on June 21, 2024

You don't have to marshal it manually, you can use the proto lib:

// Package main ...
package main

import (
	"fmt"

	"github.com/go-rod/rod/lib/cdp"
	"github.com/go-rod/rod/lib/launcher"
	"github.com/go-rod/rod/lib/proto"
	"github.com/go-rod/rod/lib/utils"
)

func main() {
	// launch a browser
	url := launcher.New().MustLaunch()

	// create a controller
	client := cdp.New().Start(cdp.MustConnectWS(url))

	go func() {
		for range client.Event() {
			// you must consume the events
			utils.Noop()
		}
	}()

	res, err := proto.TargetCreateTarget{URL: "http://test.com"}.Call(client)
	if err != nil {
		panic(err)
	}

	fmt.Println(res.TargetID)

	_ = proto.BrowserClose{}.Call(client)
}

from rod.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.