enableXhr method
Implementation
JavascriptRuntime enableXhr() {
httpClient = httpClient ?? http.Client();
dartContext[XHR_PENDING_CALLS_KEY] = [];
ownRuntimeTimer(this, Timer.periodic(Duration(milliseconds: 40), (timer) {
// exits if there is no pending call to remote
if (!hasPendingXhrCalls()) return;
// collect the pending calls into a local variable making copies
List<dynamic> pendingCalls = List<dynamic>.from(getPendingXhrCalls()!);
// clear the global pending calls list
clearXhrPendingCalls();
// for each pending call, calls the remote http service
pendingCalls.forEach((element) async {
XhrPendingCall pendingCall = element as XhrPendingCall;
late http.Response response;
try {
final methodName = '${pendingCall.method}'.toLowerCase();
final knownMethods =
HttpMethod.values.where((e) => e.name == methodName);
switch (knownMethods.isEmpty ? null : knownMethods.first) {
case null:
// Any other method (OPTIONS, ...) is sent as it is.
final request = http.Request(
methodName == 'options' ? 'OPTIONS' : pendingCall.method!,
Uri.parse(pendingCall.url!),
)..headers.addAll(pendingCall.headers);
final body = pendingCall.body;
if (body != null) request.body = body;
response = await http.Response.fromStream(
await httpClient!.send(request),
);
break;
case HttpMethod.head:
response = await httpClient!.head(
Uri.parse(pendingCall.url!),
headers: pendingCall.headers,
);
break;
case HttpMethod.get:
response = await httpClient!.get(
Uri.parse(pendingCall.url!),
headers: pendingCall.headers,
);
break;
case HttpMethod.post:
response = await httpClient!.post(
Uri.parse(pendingCall.url!),
// null sends no body (jsonEncode(null) would send "null").
body: pendingCall.body,
headers: pendingCall.headers,
);
break;
case HttpMethod.put:
response = await httpClient!.put(
Uri.parse(pendingCall.url!),
// null sends no body (jsonEncode(null) would send "null").
body: pendingCall.body,
headers: pendingCall.headers,
);
break;
case HttpMethod.patch:
response = await httpClient!.patch(
Uri.parse(pendingCall.url!),
// null sends no body (jsonEncode(null) would send "null").
body: pendingCall.body,
headers: pendingCall.headers,
);
break;
case HttpMethod.delete:
response = await httpClient!.delete(
Uri.parse(pendingCall.url!),
headers: pendingCall.headers,
);
break;
}
} catch (e) {
// Network failure (connection refused, DNS, TLS, ...): report it
// so the JavaScript side calls onerror instead of waiting forever.
_sendXhrResult(
pendingCall.idRequest,
XmlHttpRequestResponse(
responseText: null,
responseInfo: XhtmlHttpResponseInfo(statusCode: 0, statusText: ''),
error: e.toString(),
),
);
return;
}
// Malformed UTF-8 is replaced with U+FFFD instead of throwing.
final responseText =
utf8.decode(response.bodyBytes, allowMalformed: true);
final responseInfo = XhtmlHttpResponseInfo(
statusCode: response.statusCode,
statusText: response.reasonPhrase ?? '',
);
// Copied as received; the JavaScript side normalizes the names.
response.headers.forEach(responseInfo.addResponseHeaders);
_sendXhrResult(
pendingCall.idRequest,
XmlHttpRequestResponse(
responseText: responseText,
responseInfo: responseInfo,
),
);
});
}));
final evalXhrSendNative = this.evaluate("""
var xhrRequests = {};
var idRequest = -1;
function XMLHttpRequestExtension_send_native() {
idRequest += 1;
var id = idRequest;
var cb = arguments[4];
var context = arguments[5];
xhrRequests[id] = {
callback: function(responseInfo, responseText, error) {
// A request is answered once; do not keep it (and its response).
delete xhrRequests[id];
cb(responseInfo, responseText, error);
}
};
var args = [];
args[0] = arguments[0];
args[1] = arguments[1];
args[2] = arguments[2];
args[3] = arguments[3];
args[4] = idRequest;
sendMessage('SendNative', JSON.stringify(args));
}
""");
final evalXhrResult = this.evaluate(xhrJsCode);
localContext['enableXhr'] = evalXhrResult.rawResult;
localContext['xhrSendNative'] = evalXhrSendNative.rawResult;
if (_XHR_DEBUG) print('RESULT evalXhrResult: $evalXhrResult');
this.onMessage('SendNative', (arguments) {
try {
String? method = arguments[0];
String? url = arguments[1];
dynamic headersList = arguments[2];
String? body = arguments[3]?.toString();
int? idRequest = arguments[4];
Map<String, String> headers = {};
headersList.forEach((header) {
// final headerMatch = regexpHeader.allMatches(value).first;
// String? headerName = headerMatch.group(0);
// String? headerValue = headerMatch.group(1);
// if (headerName != null) {
// headers[headerName] = headerValue ?? '';
// }
String headerKey = '${header[0]}';
headers[headerKey] = '${header[1]}';
});
(dartContext[XHR_PENDING_CALLS_KEY] as List<dynamic>).add(
XhrPendingCall(
idRequest: idRequest,
method: method,
url: url,
headers: headers,
body: body,
),
);
} catch (e) {
if (_XHR_DEBUG) print('ERROR calling sendNative on Dart: >>>> $e');
// Report the failure, or the request would never settle. Not from
// inside this handler: JavaScript is still running send().
final id = arguments is List && arguments.length > 4
? arguments[4]
: null;
if (id is int) {
Timer.run(
() => _sendXhrResult(
id,
XmlHttpRequestResponse(
responseInfo:
XhtmlHttpResponseInfo(statusCode: 0, statusText: ''),
error: e.toString(),
),
),
);
}
}
});
return this;
}