Need to add cookie to API header in opened web browser running with python selenium?

Question:

Now I am working with python selenium and I want to know one problem.
I am running js script in opened web browser

result = driver.execute_script('''
        return await fetch("https://example.com", {
            "headers": {
                "accept": "application/json",
                "accept-language": "en-US,en;q=0.9",
                "traceparent": "00-3e3ff822cf02c630cff68ed054769214-62c0b9ae093c2f05-01",
                "Referrer-Policy": "origin"
            },
            "body": null,
            "method": "GET"
            })
            .then(json => json.json());
        ''')

My problem, When I run js script and call api, the result returns "session is expired".

For fix this, Will I add cookie in fetch header?
I thought, fetch will process cookie automatically if js is running in opened web browser.

Am I wrong?

If you know about this, please answer me.

Thanks in advance.

Asked By: GlistenSTAR

||

Answers:

You can set credentials: "include" so that cookies and other credential-related info, like HTTP authentication entries and TLS client certificates are sent with the request. You can read more about it here.

Something like this should work:

return await fetch("https://example.com", {
    "headers": {
        "accept": "application/json",
        "accept-language": "en-US,en;q=0.9",
        "traceparent": "00-3e3ff822cf02c630cff68ed054769214-62c0b9ae093c2f05-01",
        "Referrer-Policy": "origin"
    },
    "body": null,
    "method": "GET",
    "credentials": "include" // <---
})
.then(json => json.json());
Answered By: Brhaka