How do i get referer from chrome extension webRequest api?

I’m trying to get complete referer from chrome extension’s webRequest api. This is how my function looks like. I need to find alternative to details.initiator, as it’s not enough precise.

//Listner to the onBeforeRequest event from webRequests api 
chrome.webRequest.onBeforeRequest.addListener(
    function(details) {

        //Checks if details url contains pixel.domain.com substring
        if (details.url.toLowerCase().indexOf('pixel.domain.com') > 0) {

            //Checks if map already contains array for this initiator
            if (pixels.get(details.initiator)) {
                var urls = pixels.get(details.initiator);
                if (!urls.includes(details.url)) {
                    pixels.set(details.initiator, [...urls, details.url]);
                }
            } else {
                //Else sets new (key, value)
                pixels.set(details.initiator, [details.url]);
            }
        }
    },
    { urls: [''] }
);

Update: It can be also alternative to webRequest api, as i just need something, what tracks all requests made by the browser. Was considering also onRequest, but i’m not sure if it’s not deprecated.

Chrome Extension to unblock a blocked url using webrequest

I am trying to unblock a blocked URL using chrome.webrequest api,I went through the api documentation and implemented.It is blocking the url ,but after it ,when i run the unblock part of the code ,it is not unblocking the url.Below,is the code for the unblocking part.Is there a way ?
chrome.webRequest.onBeforeRequest.addListener(
function(details) { return { } },
{urls: ["url to be unblocked "]},
["requestBody"]);

How to modify Host field using WebRequest API in chrome extension

I am using the below sample WebRequest API code. I checked the details variable I receive. It doens’t have Host field. How can I modify the Host field of the request? Can I write complete HTTP request on my own in chrome extension?

chrome.webRequest.onBeforeSendHeaders.addListener(function(details){
  console.log(JSON.stringify(details));
  var headers = details.requestHeaders,
  blockingResponse = {};

  // Each header parameter is stored in an array. Since Chrome
  // makes no guarantee about the contents/order of this array,
  // you'll have to iterate through it to find for the
  // 'User-Agent' element
  for( var i = 0, l = headers.length; i < l; ++i ) {
    //console.log(headers[i].name);
    if( headers[i].name == 'User-Agent' ) {
      headers[i].value = '>>> Your new user agent string here <<<';
      console.log(headers[i].value);
      break;
    }
    // If you want to modify other headers, this is the place to
    // do it. Either remove the 'break;' statement and add in more
    // conditionals or use a 'switch' statement on 'headers[i].name'
  }

  blockingResponse.requestHeaders = headers;
  return blockingResponse;
},
{urls: [ "http://*/*" ]},['requestHeaders','blocking']);

How to change http method using chrome.webRequest API

Am using chrome.webRequest API to modify incoming requests and responses. However, I recently encountered a scenario where am required to intercept a POST call and change it to a GET call. I tried changing the method in object that I get in the callback, but in vain.

 chrome.webRequest.onBeforeRequest.addListener(
        function(details) { 
          details.method='GET';
            console.log('onBeforeRequest', details);
        },
        {urls: ['http://localhost/*']},
        ["requestBody"]
    );

Any idea what I should be doing to be able to change http method using Chrome Web Request API?

Thanks
K

Error in event handler for webRequest.onBeforeSendHeaders/2: Error: Invalid value for argument 4. Property ‘$$state’: Unexpected property

I’m writing a chrome extension and I’m getting this error

Error in event handler for webRequest.onBeforeSendHeaders/2: Error: Invalid value for argument 4. Property '$$state': Unexpected property

I’m not even sure where it’s coming from so not sure what code snippet to provide to get started.

Any idea how I should even read this error message? What does the “/2” in “onBeforeSendHeaders/2” mean?

Perhaps there’s a clue in my listener (simplified for our sake. I’m really doing an ajax fetch to get data before returning a promise of the headers)

chrome.webRequest.onBeforeSendHeaders.addListener(function(details) {
    return new Promise((resolve,reject) => {
      resolve({requestHeaders: [name:'authorization',value:'...']}
    });
},
{urls: [ "" ]},
['requestHeaders','blocking']); 

Bonus question. The listener doesn’t seem to be adding the header I injected when resolved in a Promise. It works if I just return {requestHeaders: …} directly.

Thoughts?

Rx.js, handling Chrome Extension webrequest API callback functions

I’m trying to use Rx.js to handle the flow of Chrome extension webrequest API.

Each webrequest addListener() call takes a mandatory callback function as the first parameter. This sends request objects to the function. However, the callback can return a webRequest.BlockingResponse that determines the further life cycle of the request.

I’m struggling to handle the blocking response as part of the observable.

This code works well for examining all image requests, for example

onBeforeRequestHandler = function() {

        var filteredURLs = ["http://*/*", "https://*/*"]; 
        var resourceTypes = ["image"]; 
        var filter = { urls: filteredURLs, types: resourceTypes };
        var options = ["blocking"];

        return Rx.Observable.create(observer => {
            var listener = chrome.webRequest.onBeforeRequest.addListener(
                function requestHandler(obj) {
                    observer.next(obj);
                },
                filter, options);
            return unsubscribe => {
                chrome.webRequest.onBeforeRequest.removeListener(listener);
            };
        });

};

I can then use all the Rx.js operators to manipulate the requests by doing this:

var source = onBeforeRequestHandler();
source.subscribe();

etc.

However, if during the course of working the images, I wish to cancel the request, I somehow need to return a blocking response object, like this {cancel:true} to the observable that is wrapping the chrome.webRequest.onBeforeRequest.addListener callback function.

At the moment I have no clue how to do this.

Any help much appreciated.

Unpredictable results with webRequest and sendMessage APIs

I’m making a chrome extension that would:

  1. Detect a POST request
  2. Send a message to the content script that’s running in the tab that made the request
  3. Retrieve some data from the DOM and send it back with sendResponse

But most of the time I’m getting “undefined” as the message sent from sendResponse.

I’ve made a dummy extension to debug this further, and the odd part is that it only works sometimes. I wasn’t able to determine the cause of this behavior after comparing the responseHeaders of the requests.

I’ve used this for testing, clicking on the “related searches” buttons.
https://www.gamiss.com/wholesale-cheap/buckle-leather-belt/

What am I missing here?

manifest.json

{
    "manifest_version": 2,
    "content_scripts": [
      {
        "matches": [
          ""
        ],
        "all_frames": true,
        "js": ["testContent.js"]
      }
    ],
    "permissions": [
      "tabs",
      "webRequest",
      ""
    ],
    "background": {
      "scripts": ["testBackground.js"],
      "persistent": true
    }
}

testBackground.js

    chrome.webRequest.onResponseStarted.addListener(function(e){
    if(e.type === "main_frame"){

        console.log(e);

        chrome.tabs.query({
            active:true,
            currentWindow:true
        },function (tabs){
            chrome.tabs.sendMessage(tabs[0].id, {message: "Hi there..."}, function (response){
                console.log(response);
            });
        });
    }

},{ 
    urls: [""],
    types: ["main_frame"]
},["responseHeaders"]
);

testContent.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
      if (request.message == "Hi there..."){
          console.log(request.message);
        sendResponse({response: "bye bye"});
        return true;
      } else {
          sendResponse({});
      }

    });

Block the request on only one page and not on all using chrome webrequest api

I am using Chrome’s WebRequest API to block a request in chrome extension.
I am blocking a request A on Gmail webpage. But I am accessing the same request on another page, let’s say localhost, then the request is blocked there also and a message is displayed as-

localhost is blocked

Requests to the server have been blocked by an extension.
Try disabling your extensions.
ERR_BLOCKED_BY_CLIENT

I want to block the request only on Gmail and not other pages. Is it possible?

Thanks in advance!

Chrome extension blocking requests not working

I am creating a chrome extension that blocks certain URLs. My code contains only two files:

manifest.json

{
  "name": "Chrome webrequest test",
  "version": "0.1",
  "description": "A test for webrequest",
  "manifest_version": 2,
  "permissions": [
    "","webRequest","webRequestBlocking"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": true
  }
}

background.js

chrome.webRequest.onBeforeRequest.addListener(
  function(){ return {cancel: true}; },
  {
    urls: [""],
    types: ["script"]
  },
  ["blocking"]
);

However, when I open dev tools on extension, it is showing error:

Error in event handler for webRequest.onBeforeRequest/1: Error:
Invocation of form webRequestInternal.eventHandled(string, string,
string, boolean) doesn’t match definition
webRequestInternal.eventHandled(string eventName, string subEventName,
string requestId, optional object response)

What should I do to fix it?

My chrome version is: Version 63.0.3239.108 (Official Build) (64-bit)

webRequest API redirect uses http method of parent request

I’m using the webRequest-API in a WebExtension to monitor requests made by the client. This works quite well, however the API doesn’t behave as expected in case of a redirect:

In this case a POST is issued which is answered with a 302 FOUND and a new location. My browser (Firefox 57, other versions and other browsers – e.g. Chrome – act the same way) follows this redirect and now issues a GET to the new location.

enter image description here

Unfortunately the webRequest-API behaves differently: It traces the first POST (which is correct) but than handles the second request as a POST, too, whereas it should be a GET. This is a severe problem since the API traces something my browser supposedly did, which it actually did in another way…

This scenario (the browser-part) can be reproduced by following this link to surfnet.nl and choosing an IDP form the list (e.g. Academisch Medisch Centrum).

So, long story short: Why does the webRequest-API behave different form the way browsers behave? And is there a way to let it exactly trace the browser’s actions?

Interestingly the webRequest-API might do it correctly, regarding the documentation:

Even if the specification requires the method, and the body, not to be altered when the redirection is performed, not all user-agents conform here [browsers obviously change the method!], and you can still find buggy software out there. It is therefore recommended to set the 302 code only as a response for GET or HEAD methods and to use 307 Temporary Redirect instead, as the method change is explicitly prohibited in that case.
In the cases where you want the method used to be changed to GET, use 303 See Other instead.