After some messing around with your Test Page, it turned out there is more happening in the background besides setting the selected value for the product_sizes
<select>
element. There is, also, a hidden <input>
element that holds the actual selected value, so it's value has to be set as well (see code below):
manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"offline_enabled": false,
"content_scripts": [{
"matches": ["*://www.example.com/*"],
"js": ["content.js"],
"run_at": "document_end",
"all_frames": false
}]
}
content.js:
var selectedIdx = 3;
var selectSize = document.querySelector('select#product_sizes');
var hiddenSize = document.querySelector('input[type="hidden"]#pdp_selectedSize');
var addToCart = document.querySelector(
'input[type="submit"][name="pdp_addtocart"]');
if ((selectSize !== undefined) && (hiddenSize !== undefined)
&& (addToCart !== undefined)) {
selectSize.selectedIndex = 3;
hiddenSize.value = selectSize.value;
addToCart.click();
}
<UPDATE>
For selecting based on size, modify content.js like this:
var targetSize = 9.0;
var selectSize = document.querySelector('select#product_sizes');
var hiddenSize = document.querySelector('input[type="hidden"]#pdp_selectedSize');
var addToCart = document.querySelector(
'input[type="submit"][name="pdp_addtocart"]');
if ((selectSize !== undefined) && (hiddenSize !== undefined)
&& (addToCart !== undefined)) {
var targetSizeStr = targetSize.toFixed(1);
var optionFound = [].slice.call(selectSize.querySelectorAll('option'))
.some(function(opt) {
if (parseFloat(opt.value).toFixed(1) === targetSizeStr) {
hiddenSize.value = opt.value;
return true;
}
return false;
});
optionFound && addToCart.click();
}
</UPDATE>
Note: If you care about the looks of the page (i.e. not only to add the item to cart, but you want the page to look exactly the way it would look if the size was selected manually etc), there are some extra modifications you need to apply. E.g. hide the <select>
element (display: none;
), set the data-content
attribute of the <a>
element just above the <select>
to the <select>
's value and its class to size_selected
, set the addToCart <a>
's class to active_step
and maybe more.