Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created February 1, 2024 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save podhmo/bae20dc90a417592c828ff216f28693a to your computer and use it in GitHub Desktop.
Save podhmo/bae20dc90a417592c828ff216f28693a to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, `<body>
<a href="/download">download</a>
<button>download from js</button>
<script>
document.querySelector("button").addEventListener("click", () => {
window.open("/download");
})
</script>
</body>`)
})
http.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Disposition", "attachment; filename=sample.txt")
w.Header().Set("Content-Type", "plain/text")
fmt.Fprintln(w, "Hello, World!")
})
addr := ":8080"
fmt.Fprintln(os.Stderr, "listening on", addr)
if err := http.ListenAndServe(addr, nil); err != nil {
panic(err)
}
}
import * as process from 'process';
import * as path from 'path';
import * as playwright from 'playwright';
async function main() {
const browser = await playwright.chromium.launch({
headless: false,
args: ["--no-zygote", "--single-process", "--disable-extensions", "--incognito"],
downloadsPath: process.cwd() + "/downloads"
})
const context = await browser.newContext();
const page = await context.newPage();
await page.goto("http://localhost:8080/", { waitUntil: 'domcontentloaded' });
const downloadPromise = page.waitForEvent("download");
console.log("click")
await page.click("a");
const download = await downloadPromise;
download.saveAs(path.join(process.cwd(), "downloads", download.suggestedFilename()));
console.log("done")
await browser.close();
}
Promise.resolve(main()).catch(err => { console.log(err); process.exit(1); });
import * as process from 'process';
import * as path from 'path';
import * as fs from 'fs/promises';
import * as playwright from 'playwright';
async function main() {
const browser = await playwright.chromium.launch({
headless: false,
args: ["--no-zygote", "--single-process", "--disable-extensions", "--incognito"],
downloadsPath: process.cwd() + "/downloads",
})
const context = await browser.newContext();
const page = await context.newPage();
await page.goto("http://localhost:8080/", { waitUntil: 'domcontentloaded' });
console.log("click")
const downloadPromise = new Promise<playwright.APIResponse>((resolve, reject) => {
page.context().route("**/download", async (route, request) => {
console.log("\troute start", request.url())
// current page
const originalResponse = await route.fetch();
console.log("\troute internal response", request.url(), originalResponse.status())
resolve(originalResponse);
await route.fulfill({
status: originalResponse.status(), body: "ok",
})
console.log("\troute end", request.url())
}, { times: 1 })
})
await page.click("button");
const response = await downloadPromise;
await fs.writeFile(path.join(process.cwd(), "downloads", "sample.txt"), await response.body())
console.log("done")
await browser.close();
}
Promise.resolve(main()).catch(err => { console.log(err); process.exit(1); });
serve:
go build -o /tmp/xxx main.go && /tmp/xxx
tree:
tree .
click-a:
DEBUG=pw:api npx tsx main.ts
click-button:
DEBUG=pw:api npx tsx main2.ts
@podhmo
Copy link
Author

podhmo commented Feb 1, 2024

.
├── Makefile
├── downloads
│   ├── 2f86c193-1864-4ea0-9cdc-a98662898ebf
│   └── sample.txt
├── main.go
├── main.ts
└── main2.ts

window.open()で開いたものを良い感じにハンドリングできない。。なんかもう少しシンプルな方法はないのかな。。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment