diff --git a/plugins/woocommerce/changelog/51449-dev-harden-added-to-cart b/plugins/woocommerce/changelog/51449-dev-harden-added-to-cart new file mode 100644 index 00000000000..99351de4130 --- /dev/null +++ b/plugins/woocommerce/changelog/51449-dev-harden-added-to-cart @@ -0,0 +1,4 @@ +Significance: patch +Type: fix + +Fix bug where manually triggering `added_to_cart` event without a button element caused an Exception. \ No newline at end of file diff --git a/plugins/woocommerce/client/legacy/js/frontend/add-to-cart.js b/plugins/woocommerce/client/legacy/js/frontend/add-to-cart.js index a99e4394750..dd2e0872c86 100644 --- a/plugins/woocommerce/client/legacy/js/frontend/add-to-cart.js +++ b/plugins/woocommerce/client/legacy/js/frontend/add-to-cart.js @@ -173,6 +173,8 @@ jQuery( function( $ ) { * Update cart page elements after add to cart events. */ AddToCartHandler.prototype.updateButton = function( e, fragments, cart_hash, $button ) { + // Some themes and plugins manually trigger added_to_cart without passing a button element, which in turn calls this function. + // If there is no button we don't want to crash. $button = typeof $button === 'undefined' ? false : $button; if ( $button ) { @@ -222,19 +224,25 @@ jQuery( function( $ ) { * Update cart live region message after add/remove cart events. */ AddToCartHandler.prototype.alertCartUpdated = function( e, fragments, cart_hash, $button ) { - var message = $button.data( 'success_message' ); + // Some themes and plugins manually trigger added_to_cart without passing a button element, which in turn calls this function. + // If there is no button we don't want to crash. + $button = typeof $button === 'undefined' ? false : $button; - if ( !message ) { - return; - } + if ( $button ) { + var message = $button.data( 'success_message' ); + + if ( !message ) { + return; + } - // If the response after adding/removing an item to/from the cart is really fast, - // screen readers may not have time to identify the changes in the live region element. - // So, we add a delay to ensure an interval between messages. - e.data.addToCartHandler.$liveRegion - .delay(1000) - .text( message ) - .attr( 'aria-relevant', 'all' ); + // If the response after adding/removing an item to/from the cart is really fast, + // screen readers may not have time to identify the changes in the live region element. + // So, we add a delay to ensure an interval between messages. + e.data.addToCartHandler.$liveRegion + .delay(1000) + .text( message ) + .attr( 'aria-relevant', 'all' ); + } }; /**