all files / src/gatherers/ offline.js

25% Statements 4/16
100% Branches 0/0
20% Functions 1/5
25% Lines 4/16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77                                                                                                                                                 
/**
 * @license
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
/* global XMLHttpRequest, __returnResults */
 
'use strict';
 
const Gather = require('./gather');
 
// *WARNING* do not use fetch.. due to it requiring window focus to fire.
// Request the current page by issuing a XMLHttpRequest request to ''
// and storing the status code on the window.
const requestPage = function() {
  const oReq = new XMLHttpRequest();
  oReq.onload = oReq.onerror = e => {
    // __returnResults is injected by driver.evaluateAsync
    __returnResults(e.currentTarget.status);
  };
  oReq.open('GET', '');
  oReq.send();
};
 
class Offline extends Gather {
  get name() {
    return 'offlineResponseCode';
  }
 
  static goOffline(driver) {
    return driver.sendCommand('Network.emulateNetworkConditions', {
      offline: true,
      // values of 0 remove any active throttling. crbug.com/456324#c9
      latency: 0,
      downloadThroughput: 0,
      uploadThroughput: 0
    });
  }
 
  static goOnline(driver) {
    return driver.sendCommand('Network.emulateNetworkConditions', {
      offline: false,
      latency: 0,
      downloadThroughput: 0,
      uploadThroughput: 0
    });
  }
 
  afterReloadPageLoad(options) {
    const driver = options.driver;
 
    // TODO eventually we will want to walk all network
    // requests that the page initially made and retry them.
    return Offline
        .goOffline(driver)
        .then(_ => driver.evaluateAsync(`(${requestPage.toString()}())`))
        .then(offlineResponseCode => {
          this.artifact = offlineResponseCode;
        })
        .then(_ => Offline.goOnline(driver));
  }
}
 
module.exports = Offline;