From b8e6d578f6790d44aebe1678d63e2ce5728c1422 Mon Sep 17 00:00:00 2001 From: desperatee Date: Wed, 1 Jul 2026 01:36:39 +0200 Subject: [PATCH 1/2] fix: concurrency bugs, license, docs, and CI Code review fixes: - Fix routeInjecting race condition: use atomic.Bool.CompareAndSwap instead of bare bool read-check-write - Fix pipeTransport.Close() race: replace manual channel-close check with sync.Once (consistent with rest of codebase) - Fix global logger mutation: driver.log() now reads d.options.Logger instead of mutating package-level var. Default logger writes to options.Stderr via slog.TextHandler - Fix transformRunOptions mutating caller's *RunOptions: clone before applying defaults so concurrent callers sharing one RunOptions don't race - Fix Verbose default being lost when caller passes any RunOptions - Add isolatedContext: true to EvalOnSelector and element_handle eval methods for consistency with all other evaluate methods - Reuse safeJoin in downloadPatchrightCore instead of duplicating traversal guard - Remove dead code in installInjectRoute (both if/else branches were identical) Other changes: - LICENSE: change from MIT to Apache-2.0 (matching Patchright upstream) - Add docs/llm-guide.md: concise LLM-friendly reference with anti-detection best practices - Add .github/workflows/ci.yml: build, vet, unit + integration tests on Go 1.22 and 1.23 --- .github/workflows/ci.yml | 56 ++++++++++ LICENSE | 213 +++++++++++++++++++++++++++++++---- docs/llm-guide.md | 232 +++++++++++++++++++++++++++++++++++++++ element_handle.go | 14 ++- frame.go | 7 +- page.go | 15 +-- run.go | 24 ++-- transport.go | 20 ++-- 8 files changed, 512 insertions(+), 69 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 docs/llm-guide.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..5692ba4 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,56 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + go-version: ['1.22', '1.23'] + steps: + - uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: ${{ matrix.go-version }} + + - name: Build + run: go build ./... + + - name: Vet + run: go vet ./... + + unit-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: '1.23' + + - name: Unit tests + run: go test -run "TestGetNodeExecutable|TestGetDriverCliJs|TestNodePlatformSuffix|TestPatchDriverBundle|TestNpmRegistryEnv|TestRunOptionsRedirectStderr" ./... -v -count=1 + + integration-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: '1.23' + + - name: Install driver and browsers + run: go run ./cmd/patchright install chromium + + - name: Integration tests + run: go test -run "TestDriverInstall|TestShouldNotHangWhenPlaywrightUnexpectedExit" ./... -v -count=1 -timeout 120s diff --git a/LICENSE b/LICENSE index d4f29b3..1ece013 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,192 @@ -MIT License - -Copyright (c) 2020 Max Schmitt - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by the Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding any notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2024 Vinyzu + Copyright 2020 Max Schmitt (playwright-go) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/docs/llm-guide.md b/docs/llm-guide.md new file mode 100644 index 0000000..f147299 --- /dev/null +++ b/docs/llm-guide.md @@ -0,0 +1,232 @@ +# patchright-go LLM Quick Reference + +Concise reference for using patchright-go with LLMs. Import as: +```go +import patchright "github.com/status403com/patchright-go" +``` + +## Install driver + browser (one-time) + +```go +patchright.Install(&patchright.RunOptions{ + Browsers: []string{"chromium"}, +}) +``` + +## Start and stop + +```go +pw, err := patchright.Run() +if err != nil { log.Fatal(err) } +defer pw.Stop() +``` + +## Launch browser + +```go +// Headless (default) +browser, err := pw.Chromium.Launch() + +// Headed +browser, err := pw.Chromium.Launch(patchright.BrowserTypeLaunchOptions{ + Headless: patchright.Bool(false), +}) + +// Use Google Chrome instead of Chromium (recommended) +browser, err := pw.Chromium.Launch(patchright.BrowserTypeLaunchOptions{ + Channel: patchright.String("chrome"), +}) + +defer browser.Close() +``` + +## Create page and navigate + +```go +page, err := browser.NewPage() +_, err = page.Goto("https://example.com") +title, err := page.Title() +``` + +## Create context with options + +```go +context, err := browser.NewContext(patchright.BrowserNewContextOptions{ + UserAgent: patchright.String("custom-ua"), + Viewport: &patchright.Size{Width: 1920, Height: 1080}, +}) +page, err := context.NewPage() +``` + +## Evaluate JavaScript + +```go +// Return value +result, err := page.Evaluate("() => document.title") + +// With argument +result, err := page.Evaluate("(x) => x * 2", 21) + +// Return handle +handle, err := page.EvaluateHandle("() => document") +``` + +All evaluate methods automatically use isolated execution contexts (Patchright's anti-detection feature). + +## Anti-detection best practices + +Patchright patches the driver but you should also configure the browser correctly: + +```go +browser, err := pw.Chromium.Launch(patchright.BrowserTypeLaunchOptions{ + Channel: patchright.String("chrome"), // use real Chrome, not bare Chromium + Headless: patchright.Bool(true), +}) + +context, err := browser.NewContext(patchright.BrowserNewContextOptions{ + UserAgent: patchright.String("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.7827.55 Safari/537.36"), + Viewport: &patchright.Size{Width: 1920, Height: 1080}, + Locale: patchright.String("en-US"), +}) + +page, err := context.NewPage() +``` + +Key rules: +1. **Use `Channel: "chrome"`** - Google Chrome is harder to fingerprint than bare Chromium +2. **Set a realistic user agent** matching the Chrome version you installed +3. **Set viewport** to a common resolution (1920x1080, 1366x768, etc) +4. **Set locale** to match target site region +5. **Use `NewContext`** instead of `NewPage` directly on browser for full control +6. **Wait properly** - use `WaitUntilStateDomcontentloaded` instead of `WaitUntilStateNetworkidle` for sites with heavy analytics + +Without these, sites with advanced protection (Akamai, PerimeterX, Datadome) may still detect you despite Patchright's patches. + +## Click, type, fill + +```go +page.Click("button#submit") +page.Fill("input[name=email]", "test@example.com") +page.Type("input[name=search]", "query") +page.Press("input", "Enter") +``` + +## Wait for elements + +```go +page.WaitForSelector("div.loaded") +page.WaitForLoadState(patchright.LoadStateNetworkidle) +``` + +## Locators (preferred) + +```go +loc := page.Locator("button.submit") +loc.Click() +text, err := loc.TextContent() +loc.Fill("value") +``` + +## Screenshots + +```go +// Full page +page.Screenshot(patchright.PageScreenshotOptions{ + Path: patchright.String("page.png"), + FullPage: patchright.Bool(true), +}) + +// Element +loc.Screenshot(patchright.LocatorScreenshotOptions{ + Path: patchright.String("element.png"), +}) +``` + +## PDF (headless only) + +```go +page.PDF(patchright.PagePDFOptions{ + Path: patchright.String("page.pdf"), +}) +``` + +## Network interception + +```go +page.Route("**/*.png", func(route patchright.Route) { + route.Abort() +}) + +page.Route("**/api/**", func(route patchright.Route) { + route.Continue() +}) +``` + +## Multiple pages / contexts + +```go +// Multiple pages in same browser +page1, _ := browser.NewPage() +page2, _ := browser.NewPage() + +// Isolated contexts (separate cookies, storage) +ctx1, _ := browser.NewContext() +ctx2, _ := browser.NewContext() +p1, _ := ctx1.NewPage() +p2, _ := ctx2.NewPage() +``` + +## Concurrent browsers + +```go +pw, _ := patchright.Run() +defer pw.Stop() + +var wg sync.WaitGroup +for i := 0; i < 10; i++ { + wg.Add(1) + go func() { + defer wg.Done() + browser, _ := pw.Chromium.Launch() + defer browser.Close() + page, _ := browser.NewPage() + page.Goto("https://example.com") + }() +} +wg.Wait() +``` + +## Pointer helpers + +patchright-go uses pointer types for optional fields. Helpers: +```go +patchright.String("value") // *string +patchright.Bool(true) // *bool +patchright.Float(1000) // *float64 +patchright.Int(5) // *int +``` + +## Key types + +| Type | Description | +|------|-------------| +| `*Patchright` | Main instance from `Run()` | +| `BrowserType` | `pw.Chromium` | +| `Browser` | From `Launch()` | +| `BrowserContext` | From `NewContext()` | +| `Page` | From `NewPage()` | +| `Locator` | From `page.Locator()` | +| `Route` | In route handlers | +| `Frame` | From `page.MainFrame()` | + +## Env vars (all optional) + +| Var | Purpose | +|-----|---------| +| `PATCHRIGHT_DRIVER_PATH` | Override driver directory | +| `PATCHRIGHT_NODEJS_PATH` | Custom Node.js binary | +| `PATCHRIGHT_CLI_PATH` | Custom cli.js path | +| `PATCHRIGHT_NPM_REGISTRY` | npm mirror | +| `NODE_MIRROR` | Node.js download mirror | + +All env vars can also be set via `RunOptions` struct fields (which take precedence). diff --git a/element_handle.go b/element_handle.go index b67115c..0a37666 100644 --- a/element_handle.go +++ b/element_handle.go @@ -136,9 +136,10 @@ func (e *elementHandleImpl) EvalOnSelector(selector string, expression string, o arg = options[0] } result, err := e.channel.Send("evalOnSelector", map[string]any{ - "selector": selector, - "expression": expression, - "arg": serializeArgument(arg), + "selector": selector, + "expression": expression, + "arg": serializeArgument(arg), + "isolatedContext": true, }) if err != nil { return nil, err @@ -152,9 +153,10 @@ func (e *elementHandleImpl) EvalOnSelectorAll(selector string, expression string arg = options[0] } result, err := e.channel.Send("evalOnSelectorAll", map[string]any{ - "selector": selector, - "expression": expression, - "arg": serializeArgument(arg), + "selector": selector, + "expression": expression, + "arg": serializeArgument(arg), + "isolatedContext": true, }) if err != nil { return nil, err diff --git a/frame.go b/frame.go index 0508139..4f8bc53 100644 --- a/frame.go +++ b/frame.go @@ -372,9 +372,10 @@ func (f *frameImpl) Evaluate(expression string, options ...any) (any, error) { func (f *frameImpl) EvalOnSelector(selector string, expression string, arg any, options ...FrameEvalOnSelectorOptions) (any, error) { params := map[string]any{ - "selector": selector, - "expression": expression, - "arg": serializeArgument(arg), + "selector": selector, + "expression": expression, + "arg": serializeArgument(arg), + "isolatedContext": true, } if len(options) == 1 && options[0].Strict != nil { params["strict"] = *options[0].Strict diff --git a/page.go b/page.go index a3e1c5b..b21239f 100644 --- a/page.go +++ b/page.go @@ -7,7 +7,6 @@ import ( "os" "path/filepath" "slices" - "strings" "sync" "sync/atomic" @@ -38,7 +37,7 @@ type pageImpl struct { locatorHandlers map[float64]*locatorHandlerEntry localStorage *webStorageImpl sessionStorage *webStorageImpl - routeInjecting bool + routeInjecting atomic.Bool } func (p *pageImpl) LocalStorage() WebStorage { @@ -814,19 +813,11 @@ func (p *pageImpl) IsClosed() bool { } func (p *pageImpl) installInjectRoute() error { - if p.routeInjecting { + if !p.routeInjecting.CompareAndSwap(false, true) { return nil } - p.routeInjecting = true return p.Route("**/*", func(route Route) { - req := route.Request() - resourceType := req.ResourceType() - url := req.URL() - if resourceType == "document" && (strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://")) { - route.Fallback(RouteFallbackOptions{}) - } else { - route.Fallback(RouteFallbackOptions{}) - } + _ = route.Fallback(RouteFallbackOptions{}) }) } diff --git a/run.go b/run.go index 5dd0427..c9df118 100644 --- a/run.go +++ b/run.go @@ -8,7 +8,6 @@ import ( "errors" "fmt" "io" - "log" "log/slog" "net/http" "os" @@ -249,12 +248,10 @@ func (d *PatchrightDriver) downloadPatchrightCore() error { if header.Typeflag != tar.TypeReg || !strings.HasPrefix(header.Name, "package/") { continue } - // Strip "package/" prefix so files land directly in the target dir. relativePath := strings.TrimPrefix(header.Name, "package/") - diskPath := filepath.Join(nodeModulesDir, relativePath) - prefix := filepath.Clean(nodeModulesDir) + string(os.PathSeparator) - if diskPath != filepath.Clean(nodeModulesDir) && !strings.HasPrefix(diskPath, prefix) { - return fmt.Errorf("invalid path in archive: %s", header.Name) + diskPath, err := safeJoin(nodeModulesDir, relativePath) + if err != nil { + return err } if err := writeFileFromReader(diskPath, tarReader, header.FileInfo().Mode()); err != nil { return err @@ -267,7 +264,6 @@ func (d *PatchrightDriver) downloadPatchrightCore() error { return nil } -// downloadNode downloads the per-platform Node.js binary from nodejs.org and // downloadNode downloads the per-platform Node.js binary. It is a no-op when // NodeJSPath is set or PATCHRIGHT_NODEJS_PATH env var is set. func (d *PatchrightDriver) downloadNode() error { @@ -354,7 +350,7 @@ func (d *PatchrightDriver) patchDriverBundle() error { func (d *PatchrightDriver) log(msg string, args ...any) { if d.options.Verbose { - logger.Info(msg, args...) + d.options.Logger.Info(msg, args...) } } @@ -480,11 +476,11 @@ func Run(options ...*RunOptions) (*Patchright, error) { } func transformRunOptions(options ...*RunOptions) (*RunOptions, error) { - option := &RunOptions{ + option := RunOptions{ Verbose: true, } if len(options) == 1 { - option = options[0] + option = *options[0] } if option.OnlyInstallShell && option.NoInstallShell { return nil, fmt.Errorf("OnlyInstallShell and NoInstallShell cannot be set at the same time") @@ -504,13 +500,11 @@ func transformRunOptions(options ...*RunOptions) (*RunOptions, error) { } if option.Stderr == nil { option.Stderr = os.Stderr - } else if option.Logger == nil { - log.SetOutput(option.Stderr) } - if option.Logger != nil { - logger = option.Logger + if option.Logger == nil { + option.Logger = slog.New(slog.NewTextHandler(option.Stderr, nil)) } - return option, nil + return &option, nil } func getNodeExecutable(options *RunOptions) string { diff --git a/transport.go b/transport.go index fe5a612..928257d 100644 --- a/transport.go +++ b/transport.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "os" + "sync" "github.com/go-jose/go-jose/v3/json" ) @@ -20,6 +21,7 @@ type pipeTransport struct { writer io.WriteCloser bufReader *bufio.Reader closed chan struct{} + closeOnce sync.Once onClose func() error process *os.Process } @@ -87,12 +89,11 @@ func (t *pipeTransport) Send(msg map[string]any) error { } func (t *pipeTransport) Close() error { - select { - case <-t.closed: - return nil - default: - return t.onClose() - } + var err error + t.closeOnce.Do(func() { + err = t.onClose() + }) + return err } func (t *pipeTransport) isClosed() bool { @@ -123,15 +124,10 @@ func newPipeTransport(driver *PatchrightDriver, stderr io.Writer) (transport, er t.bufReader = bufio.NewReader(stdout) t.onClose = func() error { - select { - case <-t.closed: - default: - close(t.closed) - } + close(t.closed) if err := t.writer.Close(); err != nil { return err } - // playwright-cli will exit when its stdin is closed if err := cmd.Wait(); err != nil { return err } From dbf03fb157e81d215962726622006e032f51fe87 Mon Sep 17 00:00:00 2001 From: desperatee Date: Wed, 1 Jul 2026 01:37:28 +0200 Subject: [PATCH 2/2] fix: use correct Chrome UA format (major.0.0.0) --- docs/llm-guide.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/llm-guide.md b/docs/llm-guide.md index f147299..a7471ca 100644 --- a/docs/llm-guide.md +++ b/docs/llm-guide.md @@ -84,7 +84,7 @@ browser, err := pw.Chromium.Launch(patchright.BrowserTypeLaunchOptions{ }) context, err := browser.NewContext(patchright.BrowserNewContextOptions{ - UserAgent: patchright.String("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.7827.55 Safari/537.36"), + UserAgent: patchright.String("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36"), Viewport: &patchright.Size{Width: 1920, Height: 1080}, Locale: patchright.String("en-US"), }) @@ -94,7 +94,7 @@ page, err := context.NewPage() Key rules: 1. **Use `Channel: "chrome"`** - Google Chrome is harder to fingerprint than bare Chromium -2. **Set a realistic user agent** matching the Chrome version you installed +2. **Set a realistic user agent** - real Chrome uses major version only (e.g. `Chrome/149.0.0.0`, never `Chrome/149.0.7827.55`) 3. **Set viewport** to a common resolution (1920x1080, 1366x768, etc) 4. **Set locale** to match target site region 5. **Use `NewContext`** instead of `NewPage` directly on browser for full control