htmx-extensions icon indicating copy to clipboard operation
htmx-extensions copied to clipboard

head-support extension fails if another extension calls htmx.swap() directly

Open mkgn opened this issue 1 year ago • 2 comments

In one of my extensions I use internal method htmx.swap(). I also use head support extension as well. head-support extension has below code where it tap into htmx:afterSwap. It try to access the evt.detail.xhr and it's null in my case because I used htmx.swap() inside my extension.. I think we should execute head-support only if it has a valid xhr responce. a simple null check would do?

    htmx.defineExtension("head-support", {
        init: function(apiRef) {
            // store a reference to the internal API.
            api = apiRef;

            htmx.on('htmx:afterSwap', function(evt){
                var serverResponse = evt.detail.xhr.response;
                if (api.triggerEvent(document.body, "htmx:beforeHeadMerge", evt.detail)) {
                    mergeHead(serverResponse, evt.detail.boosted ? "merge" : "append");
                }
            })

            htmx.on('htmx:historyRestore', function(evt){
                if (api.triggerEvent(document.body, "htmx:beforeHeadMerge", evt.detail)) {
                    if (evt.detail.cacheMiss) {
                        mergeHead(evt.detail.serverResponse, "merge");
                    } else {
                        mergeHead(evt.detail.item.head, "merge");
                    }
                }
            })

            htmx.on('htmx:historyItemCreated', function(evt){
                var historyItem = evt.detail.item;
                historyItem.head = document.head.outerHTML;
            })
        }
    });

mkgn avatar Nov 26 '24 19:11 mkgn

@Telroshan is this best moved to https://github.com/bigskysoftware/htmx-extensions/issues?

I think the fix would need to be done to the head-support extension like

            htmx.on('htmx:afterSwap', function(evt){
                if (evt.detail.xhr) {
                  var serverResponse = evt.detail.xhr.response;
                  if (api.triggerEvent(document.body, "htmx:beforeHeadMerge", evt.detail)) {
                      mergeHead(serverResponse, evt.detail.boosted ? "merge" : "append");
                  }
                }
            })

So that this event only triggers for ajax request swaps.

MichaelWest22 avatar Dec 05 '24 23:12 MichaelWest22

Sure, a null check sounds good to me. Feel free to open a bugfix PR if you're interested!

Telroshan avatar Dec 06 '24 08:12 Telroshan