User Agents

Web browsers and everyday web tech, explained

Send POST Requests from Headless Chrome on the Command Line

· 4 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. 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-chrome or /usr/bin/chromium.
  2. Launch headless Chrome with remote debugging enabled. Open a terminal and run:
    chrome --headless --remote-debugging-port=9222 --user-data-dir=/tmp/chrome-debug
    Replace chrome with your actual path. The --user-data-dir ensures a fresh profile. Keep this terminal open.
  3. Get the list of open tabs. In a new terminal, run:
    curl http://localhost:9222/json
    This returns a JSON list with a webSocketDebuggerUrl for each tab. Copy the one for the blank tab (usually the first).
  4. Prepare a WebSocket client. You'll need a way to send WebSocket messages. If you have Python, use websocket-client (install with pip install websocket-client). Alternatively, use Node.js with the ws package. For simplicity, we'll use Python.
  5. 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()
  6. 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.
  7. For JSON payloads, adjust the script. Change the post_data to a JSON string and set Content-Type to application/json. For example:
    post_data = '{"name":"test"}'
    and in the fetch headers, use 'Content-Type': 'application/json'.
  8. To see the full response with status code, modify the script. Instead of r.text(), use r.text().then(t => JSON.stringify({status: r.status, body: t})).
  9. 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=new on newer Chrome versions for better compatibility.
  • To debug, add --enable-logging --v=1 to the Chrome command line to see verbose output.
  • You can also use the --dump-dom flag 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' and credentials: '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 webSocketDebuggerUrl is 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.consoleAPICalled events.
  • 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.