Skip to content

Commit

Permalink
Intercept XMLHttpRequest network operations and gather their informat…
Browse files Browse the repository at this point in the history
…ion in inspector tool

Summary:
This diff
- creates `XHRInterceptor` to intercept all XMLHttpRequest network operations in React Native by monkey-patching.
- enables `XHRInterceptor` in RN development tool "inspector".

This interception and inspector tool work well on both Android and iOS. And this supports interception on any network API based on XMLHttpRequest, especially the Fetch API.

By now, we can intercept 12 information fields of a XMLHttpRequest including method, url, data sent, status, response type, response size, requestHeaders, responseHeaders, response, responseURL, responseType and timeout.

Follow-up:
- Will add UIs in the inspector on top of this diff, to display all the network operation information. (Not in this diff just to make this shorter)
- Will extend this to gather other valuable information towards one XMLHttpRequest.
- Should support other network request APIs like WebSocket.

Reviewed By: davidaurelio

Differential Revision: D3598873

fbshipit-source-id: 3221050ab2ebd876a718fc326646c344d0944a5f
  • Loading branch information
Siqi Liu authored and Facebook Github Bot 7 committed Jul 27, 2016
1 parent 28cf179 commit f20d5ed
Show file tree
Hide file tree
Showing 4 changed files with 298 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Libraries/Inspector/Inspector.js
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ class Inspector extends React.Component {
perfing: bool, perfing: bool,
inspected: any, inspected: any,
inspectedViewTag: any, inspectedViewTag: any,
networking: bool,
}; };


_subs: ?Array<() => void>; _subs: ?Array<() => void>;
Expand All @@ -60,6 +61,7 @@ class Inspector extends React.Component {
inspected: null, inspected: null,
selection: null, selection: null,
inspectedViewTag: this.props.inspectedViewTag, inspectedViewTag: this.props.inspectedViewTag,
networking: false,
}; };
} }


Expand Down Expand Up @@ -174,6 +176,7 @@ class Inspector extends React.Component {
perfing: val, perfing: val,
inspecting: false, inspecting: false,
inspected: null, inspected: null,
networking: false,
}); });
} }


Expand All @@ -191,6 +194,15 @@ class Inspector extends React.Component {
}); });
} }


setNetworking(val: bool) {
this.setState({
networking: val,
perfing: false,
inspecting: false,
inspected: null,
});
}

render() { render() {
var panelContainerStyle = (this.state.panelPos === 'bottom') ? {bottom: 0} : {top: 0}; var panelContainerStyle = (this.state.panelPos === 'bottom') ? {bottom: 0} : {top: 0};
return ( return (
Expand All @@ -214,6 +226,8 @@ class Inspector extends React.Component {
setSelection={this.setSelection.bind(this)} setSelection={this.setSelection.bind(this)}
touchTargetting={Touchable.TOUCH_TARGET_DEBUG} touchTargetting={Touchable.TOUCH_TARGET_DEBUG}
setTouchTargetting={this.setTouchTargetting.bind(this)} setTouchTargetting={this.setTouchTargetting.bind(this)}
networking={this.state.networking}
setNetworking={this.setNetworking.bind(this)}
/> />
</View> </View>
</View> </View>
Expand Down
11 changes: 11 additions & 0 deletions Libraries/Inspector/InspectorPanel.js
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ var ElementProperties = require('ElementProperties');
var PerformanceOverlay = require('PerformanceOverlay'); var PerformanceOverlay = require('PerformanceOverlay');
var Touchable = require('Touchable'); var Touchable = require('Touchable');
var TouchableHighlight = require('TouchableHighlight'); var TouchableHighlight = require('TouchableHighlight');
var NetworkOverlay = require('NetworkOverlay');


var PropTypes = React.PropTypes; var PropTypes = React.PropTypes;


Expand Down Expand Up @@ -51,6 +52,10 @@ class InspectorPanel extends React.Component {
contents = ( contents = (
<PerformanceOverlay /> <PerformanceOverlay />
); );
} else if (this.props.networking) {
contents = (
<NetworkOverlay />
);
} else { } else {
contents = ( contents = (
<View style={styles.waiting}> <View style={styles.waiting}>
Expand All @@ -71,6 +76,10 @@ class InspectorPanel extends React.Component {
pressed={this.props.perfing} pressed={this.props.perfing}
onClick={this.props.setPerfing} onClick={this.props.setPerfing}
/> />
<Button title={'Network'}
pressed={this.props.networking}
onClick={this.props.setNetworking}
/>
<Button title={'Touchables'} <Button title={'Touchables'}
pressed={this.props.touchTargetting} pressed={this.props.touchTargetting}
onClick={this.props.setTouchTargetting} onClick={this.props.setTouchTargetting}
Expand All @@ -90,6 +99,8 @@ InspectorPanel.propTypes = {
setPerfing: PropTypes.func, setPerfing: PropTypes.func,
touchTargetting: PropTypes.bool, touchTargetting: PropTypes.bool,
setTouchTargetting: PropTypes.func, setTouchTargetting: PropTypes.func,
networking: PropTypes.bool,
setNetworking: PropTypes.func,
}; };


class Button extends React.Component { class Button extends React.Component {
Expand Down
124 changes: 124 additions & 0 deletions Libraries/Inspector/NetworkOverlay.js
Original file line number Original file line Diff line number Diff line change
@@ -0,0 +1,124 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule NetworkOverlay
* @flow
*/
'use strict';

const React = require('React');
const StyleSheet = require('StyleSheet');
const View = require('View');
const XHRInterceptor = require('XHRInterceptor');

type NetworkRequestInfo = {
url?: string,
method?: string,
status?: number,
dataSent?: any,
responseContentType?: string,
responseSize?: number,
requestHeaders?: Object,
responseHeaders?: string,
response?: Object | string,
responseURL?: string,
responseType?: string,
timeout?: number,
};

/**
* Show all the intercepted network requests over the InspectorPanel.
*/
class NetworkOverlay extends React.Component {
_requests: Array<NetworkRequestInfo>;

constructor(props: Object) {
super(props);
this._requests = [];
}

_enableInterception(): void {
if (XHRInterceptor.isInterceptorEnabled()) {
return;
}
// Show the network request item in listView as soon as it was opened.
XHRInterceptor.setOpenCallback(function(method, url, xhr) {
// Add one private `_index` property to identify the xhr object,
// so that we can distinguish different xhr objects in callbacks.
xhr._index = this._requests.length;
const _xhr: NetworkRequestInfo = {'method': method, 'url': url};
this._requests = this._requests.concat(_xhr);
}.bind(this));

XHRInterceptor.setRequestHeaderCallback(function(header, value, xhr) {
if (!this._requests[xhr._index].requestHeaders) {
this._requests[xhr._index].requestHeaders = {};
}
this._requests[xhr._index].requestHeaders[header] = value;
}.bind(this));

XHRInterceptor.setSendCallback(function(data, xhr) {
this._requests[xhr._index].dataSent = data;
}.bind(this));

XHRInterceptor.setHeaderReceivedCallback(
function(type, size, responseHeaders, xhr) {
this._requests[xhr._index].responseContentType = type;
this._requests[xhr._index].responseSize = size;
this._requests[xhr._index].responseHeaders = responseHeaders;
}.bind(this)
);

XHRInterceptor.setResponseCallback(
function(
status,
timeout,
response,
responseURL,
responseType,
xhr,
) {
this._requests[xhr._index].status = status;
this._requests[xhr._index].timeout = timeout;
this._requests[xhr._index].response = response;
this._requests[xhr._index].responseURL = responseURL;
this._requests[xhr._index].responseType = responseType;
}.bind(this)
);

// Fire above callbacks.
XHRInterceptor.enableInterception();
}

componentDidMount() {
this._enableInterception();
}

componentWillUnmount() {
XHRInterceptor.disableInterception();
}

render() {
return (
<View style={styles.container}>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
height: 100,
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 5,
paddingRight: 5,
},
});

module.exports = NetworkOverlay;
149 changes: 149 additions & 0 deletions Libraries/Utilities/XHRInterceptor.js
Original file line number Original file line Diff line number Diff line change
@@ -0,0 +1,149 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule XHRInterceptor
*/
'use strict';

const XMLHttpRequest = require('XMLHttpRequest');
const originalXHROpen = XMLHttpRequest.prototype.open;
const originalXHRSend = XMLHttpRequest.prototype.send;
const originalXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;

var openCallback;
var sendCallback;
var requestHeaderCallback;
var headerReceivedCallback;
var responseCallback;

var isInterceptorEnabled = false;

/**
* A network interceptor which monkey-patches XMLHttpRequest methods
* to gather all network requests/responses, in order to show their
* information in the React Native inspector development tool.
* This supports interception with XMLHttpRequest API, including Fetch API
* and any other third party libraries that depend on XMLHttpRequest.
*/
const XHRInterceptor = {
/**
* Invoked before XMLHttpRequest.open(...) is called.
*/
setOpenCallback(callback) {
openCallback = callback;
},

/**
* Invoked before XMLHttpRequest.send(...) is called.
*/
setSendCallback(callback) {
sendCallback = callback;
},

/**
* Invoked after xhr's readyState becomes xhr.HEADERS_RECEIVED.
*/
setHeaderReceivedCallback(callback) {
headerReceivedCallback = callback;
},

/**
* Invoked after xhr's readyState becomes xhr.DONE.
*/
setResponseCallback(callback) {
responseCallback = callback;
},

/**
* Invoked before XMLHttpRequest.setRequestHeader(...) is called.
*/
setRequestHeaderCallback(callback) {
requestHeaderCallback = callback;
},

isInterceptorEnabled() {
return isInterceptorEnabled;
},

enableInterception() {
if (isInterceptorEnabled) {
return;
}
// Override `open` method for all XHR requests to intercept the request
// method and url, then pass them through the `openCallback`.
XMLHttpRequest.prototype.open = function(method, url) {
openCallback(method, url, this);
originalXHROpen.apply(this, arguments);
};

// Override `setRequestHeader` method for all XHR requests to intercept
// the request headers, then pass them through the `openCallback`.
XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
requestHeaderCallback(header, value, this);
originalXHRSetRequestHeader.apply(this, arguments);
};

// Override `send` method of all XHR requests to intercept the data sent,
// register listeners to intercept the response, and invoke the callbacks.
XMLHttpRequest.prototype.send = function(data) {
sendCallback(data, this);
if (this.addEventListener) {
this.addEventListener('readystatechange', () => {
if (this.readyState === this.HEADERS_RECEIVED) {
const contentTypeString = this.getResponseHeader('Content-Type');
const contentLengthString =
this.getResponseHeader('Content-Length');
let responseContentType, responseSize;
if (contentTypeString) {
responseContentType = contentTypeString.split(';')[0];
}
if (contentLengthString) {
responseSize = parseInt(contentLengthString, 10);
}
headerReceivedCallback(
responseContentType,
responseSize,
this.getAllResponseHeaders(),
this,
);
}
if (this.readyState === this.DONE) {
responseCallback(
this.status,
this.timeout,
this.response,
this.responseURL,
this.responseType,
this,
);
}
}, false);
}
originalXHRSend.apply(this, arguments);
};
isInterceptorEnabled = true;
},

// Unpatch XMLHttpRequest methods and remove the callbacks.
disableInterception() {
if (!isInterceptorEnabled) {
return;
}
isInterceptorEnabled = false;
XMLHttpRequest.prototype.send = originalXHRSend;
XMLHttpRequest.prototype.open = originalXHROpen;
XMLHttpRequest.prototype.setRequestHeader = originalXHRSetRequestHeader;
responseCallback = null;
openCallback = null;
sendCallback = null;
headerReceivedCallback = null;
requestHeaderCallback = null;
},
};

module.exports = XHRInterceptor;

0 comments on commit f20d5ed

Please sign in to comment.