简体   繁体   中英

Intercept HTTP request body from chrome extension

I'm aware that chrome.webRequest.onBeforeRequest allows a request to be intercepted, analyzed and blocked, but it only allows access to the request headers, and not the request body (as far as i know).

Sample use case: think intercepting form values.

It seems there is a API change proposal here suggesting exactly this.

Is there another way this could be accomplished?

Thanks.

This functionality has been added to the API now, see the documentation .

In order to access the body you need to do the following:

chrome.webRequest.onBeforeRequest.addListener(
    function(details)
    {
        console.log(details.requestBody);
    },
    {urls: ["https://myurlhere.com/*"]},
    ['requestBody']
);

Here is what I did

  1. I used the requestBody to get the post requests body
  2. I used a decoder the parse the body into a string

Here is an example

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        if(details.method == "POST")
        // Use this to decode the body of your post
            var postedString = decodeURIComponent(String.fromCharCode.apply(null,
                                      new Uint8Array(details.requestBody.raw[0].bytes)));
           console.log(postedString)

    },
    {urls: ["<all_urls>"]},
    ["blocking", "requestBody"]
);

While you may not be able to intercept, you can use standard AJAX approach to duct-tape it. Instead of making the href request see if you can make an asynchronous call and save it to an HTML object that isn't presented. Then scrape/read/parse/whatever your body criteria is, and if it passes, push that body object back up to the current window/page.

Storing the content in a suppressed element and then using that same element for content would allow you to avoid making duplicate calls. The downside is that you will get the full content for stuff you won't end up using. That may or may not be a bandwidth/speed performance issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM