Magento2 Product ID – How to Extract Currently Selected Product ID or SKU on Product Page

javascriptmagento2product

Assuming a system is using the default luma or blank themes, is it possible to programmatically extract the currently selected product ID or SKU from the product listing page.

In other words, I have a page state like this

Small Green Shirt Selected

Is there a way via javascript to examine what product SKU is currently selected? If not, is there a way to extract which attributes are currently selected and back solve from there?

So far I've been able to pull out the configurable product ID, as well as the values of the selected attributes via

jQuery('#product_addtocart_form').serializeArray()

I think Magento 1 had a javascript object that would let you use the above information to pull out a simple product ID. Maybe Magento 2 has the same?

Best Answer

It's not a super straightforward process, but I believe I found what you're looking for, all of this happens in the chrome console, so excuse the not-so-cookie-cutter solution.

I started out with: var jQ = require('jquery'); jQ('div.swatch-attribute').each(function() { console.log(this); });, which resulted in:

[<div class=​"swatch-attribute color" attribute-code=​"color" attribute-id=​"93" option-selected=​"56">​…​</div>​, <div class=​"swatch-attribute size" attribute-code=​"size" attribute-id=​"142" option-selected=​"168">​…​</div>​

then I checked the event listeners on one of these elements, two relevant ones were linked to div.swatch-opt. I also checked the js file that had these handlers, swatch-renderer.js, which has a method called mageSwatchRenderer and in that method a lot of the happiness takes place.

So.. jQ('div.swatch-opt').data('mageSwatchRenderer') and from there it's a short throw to finally getting jQ('div.swatch-opt').data('mageSwatchRenderer').options.jsonConfig which has all the relevant information. Specifically (jQ('[data-role=swatch-options]').data('mageSwatchRenderer').options.jsonConfig.index has a list of the product Ids with the options.

jQ('div.swatch-attribute').each(function() { console.log( jQ(this).attr('option-selected') ) }); will grab the currently set options, match that against the jsonConfig.index and you're set.