title: Chrome extension: how to call sync request from onBeforeRequest function
body: <p>I'm trying to intercept request to the mysite.com. Then I want to get through api.service.com actual mirror of mysite.com.</p>
  
  <p><strong>manifest.json</strong>:</p>
  
  <pre><code>{
      "name": "InterceptMySite",
      "version": "0.1",
      "description": "My first Chrome extension",
      "permissions": ["webRequest", "webRequestBlocking", "cookies",
                      "*://mysite.com/*", "*://api.service.com/*"],
      "background": {
          "scripts": ["background.js"]
      },
  
      "manifest_version": 2
  }
  </code></pre>
  
  <p><strong>background.js</strong>:</p>
  
  <pre><code>var mirror_url = false;
  function setMirrorUrl() {
      var req = new XMLHttpRequest();
      req.open('GET', 'http://api.service.com', false); // sync request
      req.send(null);
      req.onload = function() {
          mirror_url = this.getResponseHeader('Mirror-Url');
      }
      return mirror_url;
  }
  function getMirrorUrl() {
      chrome.cookies.get({url:'http://api.service.com',name:'mirror_url'}, function(cookie) {
          if ( ! cookie)
              return setMirrorUrl();
          else
              return cookie.value;
      });
  }
  chrome.webRequest.onBeforeRequest.addListener(
      function(info) {
          if(info.url.indexOf('api.service.com') != -1)
              return {cancel:false};
  
          getMirrorUrl();
  
          return {redirectUrl: info.url.replace(/mysite.com/i, mirror_url)};
      },
      // filters
      {
          urls: [
              "*://mysite.com/*",
              "*://api.service.com/*"
          ]
      },
      // extraInfoSpec
      ["blocking"]
  );
  </code></pre>
  
  <p>API returns mirror URL in the custom response header 'Mirror-Url' (body of response is empty). Also API stores mirror URL to the cookie "mirror_url" with expiration time after 3 hours from now. </p>
  
  <p>In the second and subsequent intercepted requests to the mysite.com all works fine: mysite.com URL replaced by actual mirror URL stored in the cookies.</p>
  
  <p>But in the first request to the mysite.com (when there is no cookie with mirror url) host URL replaced by "undefined" because onBeforeRequest listener returns redirectUrl <strong>before</strong> getMirrorUrl() is finished. Why? XMLHttpRequest object (in the <strong>setMirrorUrl()</strong> function) set to the <strong>sync</strong> request.</p>