// 監聽 DOM 變化
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.addedNodes.length > 0) {
mutation.addedNodes.forEach(function(node) {
if (node.nodeType === 1) {
var text = node.textContent || '';
if (text.includes('逛逛') || text.includes('立即加購') || text.includes('加購安')) {
setTimeout(function() { modifyAddBuyPopup(node); }, 100);
setTimeout(function() { modifyAddBuyPopup(node); }, 500);
}
}
});
}
});
});
if (document.body) {
observer.observe(document.body, { childList: true, subtree: true });
} else {
document.addEventListener('DOMContentLoaded', function() {
observer.observe(document.body, { childList: true, subtree: true });
});
}
})();
// 手機版加購彈窗修正 v2:攜截 /cart/add XHR,補發 peh 事件
(function() {
'use strict';
var _emitRecord = {};
function watchPeh() {
if (!window.peh) { setTimeout(watchPeh, 300); return; }
window.peh.on('product:add_to_cart', function(data) {
if (data && data[0] && data[0].variantId) {
_emitRecord[data[0].variantId] = Date.now();
}
});
}
watchPeh();
var _origOpen = XMLHttpRequest.prototype.open;
var _origSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function(method, url) {
if (url && typeof url === 'string' && url.indexOf('/cart/add') > -1) {
this._cartAddFlag = true;
}
return _origOpen.apply(this, arguments);
};
XMLHttpRequest.prototype.send = function(body) {
var xhr = this;
if (xhr._cartAddFlag) {
xhr.addEventListener('load', function() {
if (xhr.status >= 200 && xhr.status < 300) {
try {
var r = JSON.parse(xhr.responseText);
if (!r || !r.id) return;
var vid = r.id, qty = r.quantity || 1;
setTimeout(function() {
var t = _emitRecord[vid];
if (t && (Date.now() - t) < 2000) return;
if (typeof window.pullNavCart === 'function') {
try { window.pullNavCart(); } catch(e2) {}
}
if (window.peh) {
window.peh.emit('product:add_to_cart', [{variantId: vid, quantity: qty}]);
}
}, 600);
} catch(e) {}
}
});
}
return _origSend.apply(this, arguments);
};
})();