diff --git a/src/ext/ajax-header.js b/src/ext/ajax-header.js new file mode 100644 index 00000000..1891699d --- /dev/null +++ b/src/ext/ajax-header.js @@ -0,0 +1,7 @@ +htmx.defineExtension('ajax-header', { + onEvent: function (name, evt) { + if (name === "configRequest.htmx") { + evt.detail.headers['X-Requested-With'] = 'XMLHttpRequest'; + } + } +}); \ No newline at end of file diff --git a/test/ext/ajax-header.js b/test/ext/ajax-header.js new file mode 100644 index 00000000..0888ef3b --- /dev/null +++ b/test/ext/ajax-header.js @@ -0,0 +1,21 @@ +describe("ajax-header extension", function() { + beforeEach(function () { + this.server = makeServer(); + clearWorkArea(); + }); + afterEach(function () { + this.server.restore(); + clearWorkArea(); + }); + + it('Sends the X-Requested-With header', function () { + this.server.respondWith("GET", "/test", function (xhr) { + xhr.respond(200, {}, xhr.requestHeaders['X-Requested-With']) + }); + var btn = make('') + btn.click(); + this.server.respond(); + btn.innerHTML.should.equal("XMLHttpRequest"); + }); + +}); \ No newline at end of file diff --git a/test/index.html b/test/index.html index 1b47a4dd..358f207f 100644 --- a/test/index.html +++ b/test/index.html @@ -121,6 +121,8 @@ + + diff --git a/www/extensions.md b/www/extensions.md index 1c8771ce..f3633ad0 100644 --- a/www/extensions.md +++ b/www/extensions.md @@ -54,6 +54,7 @@ against `htmx` in each distribution | [`rails-method`](/extensions/rails-method) | includes the `_method` parameter in requests for rails compatibility | [`remove-me`](/extensions/remove-me) | allows you to remove an element after a given amount of time | [`include-vals`](/extensions/include-vals) | allows you to include additional values in a request +| [`ajax-header`](/extensions/ajax-header) | includes the commonly-used X-Requested-With header that identifies ajax requests in many backend frameworks diff --git a/www/extensions/ajax-header.md b/www/extensions/ajax-header.md new file mode 100644 index 00000000..39566150 --- /dev/null +++ b/www/extensions/ajax-header.md @@ -0,0 +1,22 @@ +--- +layout: layout.njk +title: > htmx - high power tools for html +--- + +## The `ajax-header` Extension + +This extension adds the X-Requested-With header to requests with the value "XMLHttpRequest". + +This header is commonly used by javascript frameworks to differentiate ajax requests from normal http requests. + +### Usage + +```html +
+ ... + +``` + +### Source + +