From faf8bb4bffb18db68296b6de64c7a9dc0da5fbd1 Mon Sep 17 00:00:00 2001 From: Tim Schilling Date: Fri, 21 Oct 2022 11:02:28 -0700 Subject: [PATCH] Auto-update History panel with JavaScript fetch requests. The fetch and XHR requests don't share internals in JavaScript. We should automatically capture both sets of requests as they occur. --- .../static/debug_toolbar/js/toolbar.js | 30 +++++++++++++++---- docs/changes.rst | 3 ++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/debug_toolbar/static/debug_toolbar/js/toolbar.js b/debug_toolbar/static/debug_toolbar/js/toolbar.js index 1c06be7fa..a1b90f388 100644 --- a/debug_toolbar/static/debug_toolbar/js/toolbar.js +++ b/debug_toolbar/static/debug_toolbar/js/toolbar.js @@ -261,6 +261,15 @@ const djdt = { document.getElementById("djDebug").dataset.sidebarUrl; const slowjax = debounce(ajax, 200); + function handleAjaxResponse(storeId) { + storeId = encodeURIComponent(storeId); + const dest = `${sidebar_url}?store_id=${storeId}`; + slowjax(dest).then(function (data) { + replaceToolbarState(storeId, data); + }); + } + + // Patch XHR / traditional AJAX requests const origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function () { this.addEventListener("load", function () { @@ -270,16 +279,25 @@ const djdt = { if ( this.getAllResponseHeaders().indexOf("djdt-store-id") >= 0 ) { - let store_id = this.getResponseHeader("djdt-store-id"); - store_id = encodeURIComponent(store_id); - const dest = `${sidebar_url}?store_id=${store_id}`; - slowjax(dest).then(function (data) { - replaceToolbarState(store_id, data); - }); + handleAjaxResponse(this.getResponseHeader("djdt-store-id")); } }); origOpen.apply(this, arguments); }; + + const origFetch = window.fetch; + window.fetch = function (url, options) { + const promise = origFetch(url, options); + promise.then(function (response) { + if (response.headers.get("djdt-store-id") !== null) { + handleAjaxResponse(response.headers.get("djdt-store-id")); + } + // Don't resolve the response via .json(). Instead + // continue to return it to allow the caller to consume as needed. + return response; + }); + return promise; + }; }, cookie: { get(key) { diff --git a/docs/changes.rst b/docs/changes.rst index 720a8c050..6f74c04b9 100644 --- a/docs/changes.rst +++ b/docs/changes.rst @@ -4,6 +4,9 @@ Change log Pending ------- +* Auto-update History panel for JavaScript ``fetch`` requests. + + 3.7.0 (2022-09-25) ------------------