Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

browser.EachEvent MustEvalOnNewDocument doesn't work #856

Closed
gopkg-dev opened this issue Apr 6, 2023 · 2 comments
Closed

browser.EachEvent MustEvalOnNewDocument doesn't work #856

gopkg-dev opened this issue Apr 6, 2023 · 2 comments
Labels
question Questions related to rod

Comments

@gopkg-dev
Copy link

gopkg-dev commented Apr 6, 2023

Rod Version: v0.112.8

The code to demonstrate your question

func Test_02(t *testing.T) {
	browser := rod.New().MustConnect()
	defer browser.MustClose()
	go browser.EachEvent(func(e *proto.TargetTargetCreated) {
		if e.TargetInfo.Type != proto.TargetTargetInfoTypePage {
			return
		}
		page := browser.MustPageFromTargetID(e.TargetInfo.TargetID)
		// Inject js to every new page
		page.MustEvalOnNewDocument(`window.addEventListener('load', () => {
document.body.innerHTML = '<h1>Hello, world!</h1><p id="test">This is my page content.</p>';
})`)
	})
	page := browser.MustPage("https://example.com/").MustWaitLoad()
	page.MustElement("#test")
	utils.Pause()
}

She did not execute js, did not modify the body.

@gopkg-dev gopkg-dev added the question Questions related to rod label Apr 6, 2023
@ysmood
Copy link
Collaborator

ysmood commented Apr 6, 2023

It's a limitation of cdp, you can't use it like this way. They don't allow you run MustEvalOnNewDocument before the page is created.

You should use MustEvalOnNewDocument like this:

	browser := rod.New().MustConnect()
	page := browser.MustPage()
	page.MustEvalOnNewDocument(`window.addEventListener('load', () => {
		document.body.innerHTML = '<h1>Hello, world!</h1><p id="test">This is my page content.</p>';
		})`)

	page.MustNavigate("https://example.com/")
	fmt.Println(page.MustElement("#test").MustText())

@gopkg-dev
Copy link
Author

Thank you for letting me know about the limitation of cdp and how to use MustEvalOnNewDocument correctly. Your suggestion to navigate to the website first and then use MustEvalOnNewDocument after the page has loaded is very helpful. I appreciate your help on this matter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Questions related to rod
Projects
None yet
Development

No branches or pull requests

2 participants