(function () {
var path = window.location.pathname;
if (!/\/categories\//.test(path)) return;
function cleanUrl(raw) {
if (!raw) return '';
return raw.replace(/^url\(["']?/, '').replace(/["']?\)$/, '').split('?')[0];
}
function extractPrice(text, attrValue) {
if (attrValue && !isNaN(attrValue)) return attrValue;
if (!text) return '';
var normalized = text.replace(/,/g, '');
var match = normalized.match(/(\d+(?:\.\d+)?)/);
return match ? match[1] : '';
}
function buildSchema() {
if (document.querySelector('script[data-schema-injected="category-itemlist"]')) return true;
var blocks = Array.prototype.slice.call(document.querySelectorAll('.product-block, .product-card, .product-item'));
if (!blocks.length) return false;
var items = [];
blocks.forEach(function (block, index) {
var linkEl = block.querySelector('a[href*="/products/"]');
var titleEl = block.querySelector('.product-block__title, .product-card__title, .product-title, .title');
var priceEl = block.querySelector('.product-block__price .money, .product-card__price .money, [data-price]');
var imgEl = block.querySelector('.boxify-image, .product-block__image img, .product-card__image img');
var name = titleEl ? titleEl.innerText.trim() : '';
var url = linkEl ? linkEl.href : '';
var price = priceEl ? extractPrice(priceEl.innerText, priceEl.getAttribute('data-price')) : '';
var image = '';
if (imgEl) {
if (imgEl.tagName === 'IMG') {
image = imgEl.src || imgEl.getAttribute('data-src') || '';
} else if (imgEl.style && imgEl.style.backgroundImage) {
image = cleanUrl(imgEl.style.backgroundImage);
}
}
if (!name || !url || !price || !image) return;
var availability = 'https://schema.org/InStock';
if (block.textContent && /售完|缺貨|Sold\s?Out/i.test(block.textContent)) {
availability = 'https://schema.org/OutOfStock';
}
items.push({
"@type": "ListItem",
"position": index + 1,
"item": {
"@type": "Product",
"name": name,
"image": [image],
"url": url,
"offers": {
"@type": "Offer",
"priceCurrency": "HKD",
"price": price,
"availability": availability,
"url": url
}
}
});
});
if (!items.length) return false;
var schema = {
"@context": "https://schema.org",
"@type": "ItemList",
"name": document.title || "Category Listing",
"itemListOrder": "https://schema.org/ItemListOrderAscending",
"numberOfItems": items.length,
"itemListElement": items
};
var script = document.createElement('script');
script.type = 'application/ld+json';
script.text = JSON.stringify(schema);
script.setAttribute('data-schema-injected', 'category-itemlist');
document.head.appendChild(script);
return true;
}
if (buildSchema()) return;
var attempts = 0;
var observer = new MutationObserver(function () {
attempts++;
if (buildSchema() || attempts > 12) observer.disconnect();
});
observer.observe(document.body, { childList: true, subtree: true });
setTimeout(function () { observer.disconnect(); }, 15000);
})();