Skip to content

Commit

Permalink
v.1.1.0, not shim request/response in fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
foo123 committed Mar 17, 2023
1 parent c69ac80 commit 086ef1e
Show file tree
Hide file tree
Showing 4 changed files with 115 additions and 109 deletions.
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Listen to any AJAX event on page with JavaScript, even by other scripts

Version: **1.0.2** (6 kB minified)
Version: **1.1.0** (6 kB minified)

![AJAX Listener](/ajaxlistener.jpg)

Expand All @@ -11,6 +11,7 @@ Version: **1.0.2** (6 kB minified)
```javascript
function mylistener(req, res)
{
// API is either 'xhr' or 'fetch'
console.log('REQUEST', 'API', req.getAPI(), 'Method', req.getMethod(), 'URL', req.getURL(), 'Headers', req.getHeaders(), 'Body', req.getBody());
console.log('RESPONSE', 'API', res.getAPI(), 'Status', res.getStatus(), 'URL', res.getURL(), 'Headers', res.getHeaders(), 'Body', res.getBody());
}
Expand All @@ -29,7 +30,7 @@ AjaxListener.install().onRequest(mylistener);
* [HtmlWidget](https://github.com/foo123/HtmlWidget) html widgets, made as simple as possible, both client and server, both desktop and mobile, can be used as (template) plugins and/or standalone for PHP, JavaScript, Python (can be used as [plugins for Contemplate](https://github.com/foo123/Contemplate/blob/master/src/js/plugins/plugins.txt))
* [Paginator](https://github.com/foo123/Paginator) simple and flexible pagination controls generator for PHP, JavaScript, Python
* [ColorPicker](https://github.com/foo123/ColorPicker) a fully-featured and versatile color picker widget
* [Pikadaytime](https://github.com/foo123/Pikadaytime) a refreshing JavaScript Datetimepicker that is ightweight, with no dependencies
* [Pikadaytime](https://github.com/foo123/Pikadaytime) a refreshing JavaScript Datetimepicker that is lightweight, with no dependencies
* [Timer](https://github.com/foo123/Timer) count down/count up JavaScript widget
* [InfoPopup](https://github.com/foo123/InfoPopup) a simple JavaScript class to show info popups easily for various items and events (Desktop and Mobile)
* [Popr2](https://github.com/foo123/Popr2) a small and simple popup menu library
Expand All @@ -43,8 +44,8 @@ AjaxListener.install().onRequest(mylistener);
* [Carousel3](https://github.com/foo123/Carousel3) HTML5 Photo Carousel using Three.js
* [Rubik3](https://github.com/foo123/Rubik3) intuitive 3D Rubik Cube with Three.js
* [MOD3](https://github.com/foo123/MOD3) JavaScript port of AS3DMod ActionScript 3D Modifier Library
* [Geometrize](https://github.com/foo123/Geometrize) Computational Geometry and Rendering Library for JavaScript
* [RT](https://github.com/foo123/RT) unified client-side real-time communication for JavaScript using XHR polling / BOSH / WebSockets / WebRTC
* [AjaxListener.js](https://github.com/foo123/AjaxListener.js): Listen to any AJAX event on page with JavaScript, even by other scripts
* [asynchronous.js](https://github.com/foo123/asynchronous.js) simple manager for asynchronous, linear, parallel, sequential and interleaved tasks for JavaScript
* [classy.js](https://github.com/foo123/classy.js) Object-Oriented mini-framework for JavaScript

145 changes: 58 additions & 87 deletions src/AjaxListener.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
/**
*
* AjaxListener.js: listen to any AJAX event on page, even by other scripts
* version 1.0.2
* version 1.1.0
* https://github.com/foo123/AjaxListener.js
*
**/
!function(root, name, factory) {
"use strict";
root[name] = factory();
if ('function' === typeof define && define.amd) define(function(req) {return root[name];});
}('undefined' !== typeof self ? self : this, 'AjaxListener', function() {
}('undefined' !== typeof self ? self : this, 'AjaxListener', function(undef) {
"use strict";

var AjaxListener = {VERSION: '1.0.2'},
var AjaxListener = {VERSION: '1.1.0'},
callbacks = [], installed = false,
HAS = Object.prototype.hasOwnProperty, FtoString = Function.prototype.toString,
HAS = Object.prototype.hasOwnProperty,
toString = Object.prototype.toString,
FtoString = Function.prototype.toString,
NL = /[\r\n]+/,
NESTED = /^[^\[\]\.]+(\[[^\[\]\.]+\])+(\[\])?$/,
BRAKET = /\[([^\[\]]+)\]/g,
Expand All @@ -26,7 +28,11 @@ var AjaxListener = {VERSION: '1.0.2'},

function get_base_url()
{
return window.location.origin + window.location.pathname/*.split('/').slice(0, -1).join('/')*/;
return window.location.origin + window.location.pathname;
}
function is_string(x)
{
return '[object String]' === toString.call(x);
}
function is_native_function(f)
{
Expand Down Expand Up @@ -165,12 +171,6 @@ function Request(api, method, _url, _headersFactory, _body)
hash: u.hash,
queryParams: u.search && u.search.length ? parse_url_params(u.search.slice(1)) : {}
};
/*
// NOT ADDED AS QUERY PARAMS!!
if (('GET' === self.getMethod()) && is_formdata(self.getBody(true)))
{
url.queryParams = extract_form_data(self.getBody(true), url.queryParams);
}*/
}
return url;
};
Expand All @@ -187,19 +187,26 @@ function Request(api, method, _url, _headersFactory, _body)
{
if (is_formdata(_body))
{
return body = extract_form_data(_body);
}
var contentType = String(self.getHeaders()['content-type'] || '');
if (-1 !== contentType.indexOf('application/x-www-form-urlencoded'))
{
body = parse_url_params(_body);
body = extract_form_data(_body);
}
else if (
-1 !== contentType.indexOf('application/json')
|| -1 !== contentType.indexOf('application/vnd.api+json')
)
else if (is_string(_body))
{
body = parse_json(_body);
var contentType = String(self.getHeaders()['content-type'] || '');
if (-1 !== contentType.indexOf('application/x-www-form-urlencoded'))
{
body = parse_url_params(_body);
}
else if (
-1 !== contentType.indexOf('application/json')
|| -1 !== contentType.indexOf('application/vnd.api+json')
)
{
body = parse_json(_body);
}
else
{
body = _body;
}
}
else
{
Expand Down Expand Up @@ -271,17 +278,24 @@ function Response(api, status, _url, _headersFactory, _body)
if (true === raw) return _body;
if (null == body && null != _body)
{
var contentType = String(self.getHeaders()['content-type'] || '');
if (-1 !== contentType.indexOf('application/x-www-form-urlencoded'))
{
body = parse_url_params(_body);
}
else if (
-1 !== contentType.indexOf('application/json')
|| -1 !== contentType.indexOf('application/vnd.api+json')
)
if (is_string(_body))
{
body = parse_json(_body);
var contentType = String(self.getHeaders()['content-type'] || '');
if (-1 !== contentType.indexOf('application/x-www-form-urlencoded'))
{
body = parse_url_params(_body);
}
else if (
-1 !== contentType.indexOf('application/json')
|| -1 !== contentType.indexOf('application/vnd.api+json')
)
{
body = parse_json(_body);
}
else
{
body = _body;
}
}
else
{
Expand All @@ -307,63 +321,20 @@ function listenerFetch(request)
{
var args = arguments, options = (1 < args.length ? args[1] : {}) || {};
return new Promise(function(resolve, reject) {
fetch.apply(window, args).then(function(response) {
if (/*response.ok &&*/ callbacks.length)
{
var getReqText, getResText = response.text.bind(response),
reqText = '', resText = '',
reqJSON = undefined, resJSON = undefined,
errReqJSON = null, errResJSON = null;
response.text = function() {return Promise.resolve(resText);};
response.json = function() {return errResJSON ? Promise.reject(errResJSON) : Promise.resolve(resJSON);};
if (request instanceof window.Request)
fetch.apply(window, args).then(function(response) {
resolve(response);
if (callbacks.length)
{
getReqText = request.text.bind(request);
request.text = function() {return Promise.resolve(reqText);};
request.json = function() {return errReqJSON ? Promise.reject(errReqJSON) : Promise.resolve(reqJSON);};
notify(
request instanceof window.Request
? new Request('fetch', request.method, request.url, factory(extract_headers, request.headers), request.body)
: new Request('fetch', options.method || 'GET', request, factory(get_headers, options.headers || {}), options.body || ''),
new Response('fetch', response.status, response.url || request.url, factory(extract_headers, response.headers), response.body)
);
}
getResText().then(function(responseText) {
resText = responseText;
try {
resJSON = JSON.parse(resText);
} catch(err) {
resJSON = undefined;
errResJSON = err;
}
if (request instanceof window.Request)
{
getReqText().then(function(requestText) {
reqText = requestText;
try {
reqJSON = JSON.parse(reqText);
} catch(err) {
reqJSON = undefined;
errReqJSON = err;
}
resolve(response);
notify(
new Request('fetch', request.method, request.url, factory(extract_headers, request.headers), requestText),
new Response('fetch', response.status, response.url || request.url, factory(extract_headers, response.headers), responseText)
);
});
}
else
{
resolve(response);
notify(
new Request('fetch', options.method || 'GET', request, factory(get_headers, options.headers || {}), options.body || ''),
new Response('fetch', response.status, response.url || request, factory(extract_headers, response.headers), responseText)
);
}
})/*.catch(function(err) {})*/;
}
else
{
resolve(response);
}
}).catch(function(err) {
reject(err);
});
}).catch(function(err) {
reject(err);
});
});
}
listenerFetch.ajaxListener = AjaxListener;
Expand Down
Loading

0 comments on commit 086ef1e

Please sign in to comment.