Possible to modify cookie values in a jQuery ajax request?

前端 未结 2 1347
小蘑菇
小蘑菇 2021-01-04 10:46

I am working on a Chrome extension that would allow users to record all HTTP requests for a site, modify pieces of the request and then resend it.

I\'m hoping to use

相关标签:
2条回答
  • 2021-01-04 11:01

    Since you're talking about a Chrome extension, you can employ webRequest API to intercept and modify your requests.

    chrome.webRequest.onBeforeSendHeaders.addListener(
      function(details) {
        /* Identify somehow that it's a request initiated by you */
    
        for (var i = 0; i < details.requestHeaders.length; i++) {
          if (details.requestHeaders[i].name === 'Cookie') {
            /* Do something with it */
            break;
          }
        }
    
        /* Add the Cookie header if it was not found */
    
        return {requestHeaders: details.requestHeaders};
      },
      {urls: ["*://*.example.com/*"]}, 
      ["blocking", "requestHeaders"]
    );
    

    This way you should be able to modify the cookies without actually modifying the browser's cookie store. I said "should" because I have not tested this solution.

    Some important points:

    • You will need permissions: "webRequest", "webRequestBlocking" and host permissions (for this example, "*://*.example.com/")
    • There's a caveat that you can't intercept your own synchronous requests, as a precaution against deadlocks. As long as your AJAX is asynchronous, it should not matter.
    • If you need to prevent Set-Cookie from the response from reaching the cookie store, you can do so by modifying the response headers in onHeadersReceived. You can use the request ID to find the corresponding response.
    0 讨论(0)
  • 2021-01-04 11:11

    It's not going to be possible to do this everywhere using jQuery.ajax().

    XMLHttpRequest doesn't allow you to modify the Cookie header (see spec), and jQuery.ajax uses XMLHttpRequest under the hood.

    And using XMLHttpRequest directly in javascript has the same issue, so no help there.

    You can add cookies to the current document and tell jQuery to tell the XHR to send cookies cross-domain with xhrFields: { withCredentials: true }, but the target site also has to have the corresponding CORS setup, which it sounds like doesn't match your use-case.

    If you want to try it out, some resources:

    Sending credentials with cross-domain posts?

    http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings (look for xhrFields)

    0 讨论(0)
提交回复
热议问题