Send POST Requests from Headless Chrome on the Command Line
In this article
This guide shows you how to send HTTP POST requests using headless Chrome from the command line. This is useful for testing APIs, automating form submissions, or debugging endpoints without opening a full browser. You'll use Chrome's built-in remote debugging protocol and a simple command-line tool like curl to drive it. No extra software beyond Chrome and a terminal is needed.
What You'll Need
- Google Chrome or Chromium installed (version 60+ for headless mode).
- A terminal (Command Prompt, PowerShell, or bash).
- Basic familiarity with command-line navigation.
- An endpoint URL that accepts POST requests (e.g., a test API).
Step-by-Step
- Find your Chrome executable path. On Windows, it's typically
C:\Program Files\Google\Chrome\Application\chrome.exe. On macOS, it's/Applications/Google Chrome.app/Contents/MacOS/Google Chrome. On Linux, it's usually/usr/bin/google-chromeor/usr/bin/chromium. - Launch headless Chrome with remote debugging enabled. Open a terminal and run:
chrome --headless --remote-debugging-port=9222 --user-data-dir=/tmp/chrome-debug
Replacechromewith your actual path. The--user-data-dirensures a fresh profile. Keep this terminal open. - Get the list of open tabs. In a new terminal, run:
curl http://localhost:9222/json
This returns a JSON list with awebSocketDebuggerUrlfor each tab. Copy the one for the blank tab (usually the first). - Prepare a WebSocket client. You'll need a way to send WebSocket messages. If you have Python, use
websocket-client(install withpip install websocket-client). Alternatively, use Node.js with thewspackage. For simplicity, we'll use Python. - Write a small script to send a POST request. Create a file named send_post.py with the following content, replacing YOUR_WS_URL with the copied URL and YOUR_API_URL with your target endpoint: import websocket, json, sys ws_url = "YOUR_WS_URL" api_url = "YOUR_API_URL" post_data = "key=value&foo=bar" # or JSON: '{"key":"value"}' ws = websocket.create_connection(ws_url) # Enable Network and Runtime ws.send(json.dumps({"id":1, "method":"Network.enable"})) ws.send(json.dumps({"id":2, "method":"Runtime.enable"})) # Execute fetch POST in the page context # Read response while True: msg = json.loads(ws.recv()) if msg.get("id") == 3: print("Response:", msg["result"]["result"]["value"]) break ws.close()
- Run the script. Execute
python send_post.py. You should see the response body printed. If the server returns JSON, it will be a string; you can parse it further. - For JSON payloads, adjust the script. Change the
post_datato a JSON string and setContent-Typetoapplication/json. For example:post_data = '{"name":"test"}'and in the fetch headers, use'Content-Type': 'application/json'. - To see the full response with status code, modify the script. Instead of
r.text(), user.text().then(t => JSON.stringify({status: r.status, body: t})). - Clean up. After testing, stop the headless Chrome process (Ctrl+C in its terminal) and delete the temporary user data directory if you created one.
Common Mistakes
- Using the wrong Chrome path. On macOS, the binary is inside the app bundle, not the executable at the root.
- Forgetting
--user-data-dir. Without it, Chrome may fail to start in headless mode if another instance is running. - Not enabling Network or Runtime. The fetch command requires the page context, which is available without enabling, but enabling is safer for more complex operations.
- Quoting issues in the script. If your POST data contains single quotes, escape them or use double quotes in the JavaScript string.
- Assuming the response is synchronous. The script waits for the correct ID, but if you send multiple commands, you must handle out-of-order responses.
Tips
- Use
--headless=newon newer Chrome versions for better compatibility. - To debug, add
--enable-logging --v=1to the Chrome command line to see verbose output. - You can also use the
--dump-domflag if you need to see the page after the POST, but that's for GET requests only. - For repeated testing, write a shell script that starts Chrome, runs the Python script, and kills Chrome automatically.
- If you need to handle redirects or cookies, use
redirect: 'follow'andcredentials: 'include'in the fetch options.
Troubleshooting
- Chrome doesn't start. Ensure no other Chrome instance is using the same debugging port. Change the port (e.g., 9223) and update the URL.
- Connection refused on port 9222. Make sure Chrome is still running and the port is correct. Check with
curl http://localhost:9222/json/version. - WebSocket connection fails. Verify the
webSocketDebuggerUrlis correct and that your Python websocket library is installed. - Script hangs. The response may never come if the fetch promise rejects. Add a timeout in the script or handle errors in the JavaScript.
- Response is undefined. Check the browser console for errors. You can capture console messages by listening to
Runtime.consoleAPICalledevents. - POST data not sent correctly. Ensure the body is properly URL-encoded or JSON-encoded, and the Content-Type header matches.
Frequently Asked Questions
Can I send POST requests without a WebSocket client?
Yes, you can use the --remote-debugging-pipe flag and communicate via stdin/stdout, but WebSocket is simpler. Alternatively, use a tool like chromedriver with Selenium, but that's heavier.
Does headless Chrome support all fetch features?
Yes, it supports the full Fetch API, including CORS, cookies, and redirects, as long as you handle them in the script.
Can I send POST requests to a localhost server?
Absolutely. Headless Chrome runs on your machine, so localhost works fine. Just ensure the server is running.
How do I send multipart/form-data?
Use the FormData object in JavaScript and pass it as the body. For example: let fd = new FormData(); fd.append('file', new Blob(['content']), 'file.txt'); fetch(url, {method:'POST', body: fd}).
Is there a way to see the request headers?
Yes, use the Network.requestWillBeSent event. You can listen to it in the WebSocket script and print the headers.
Can I run this on a server without a display?
Yes, headless Chrome is designed for that. Just ensure you have the necessary dependencies (like libnss3 on Linux) installed.