'use strict'; const WS_URL = 'ws://127.0.0.1:18792/cdp'; const TOKEN = '0537d84a67f2e43b525964bb43d93f6dfae1ec1b50946455'; const TARGET_URL = 'https://diaonline.supermercadosdia.com.ar/medios-de-pago-y-promociones'; const WS = require('/usr/lib/node_modules/openclaw/node_modules/ws').WebSocket || require('/usr/lib/node_modules/openclaw/node_modules/ws'); const ws = new WS(WS_URL, { headers: { 'x-openclaw-relay-token': TOKEN } }); let _id = 1, sessionId = null, started = false; const cbs = new Map(); const capturedLegals = []; function send(method, params, cb) { const id = _id++; const m = { id, method, params: params || {} }; if (sessionId) m.sessionId = sessionId; if (cb) cbs.set(id, cb); ws.send(JSON.stringify(m)); } function evalStr(expr, cb) { send('Runtime.evaluate', { expression: expr, returnByValue: true }, r => { if (r && r.exceptionDetails) console.error('[JS ERROR]', JSON.stringify(r.exceptionDetails).slice(0,200)); cb(r && r.result && r.result.value); }); } function sleep(ms) { return new Promise(r => setTimeout(r, ms)); } ws.on('open', () => { send('Target.getTargets', {}, res => { const target = (res.targetInfos||[]).filter(t=>t.type==='page')[0]; console.log('Attaching to tab:', target&&target.url); send('Target.attachToTarget', { targetId: target.targetId, flatten: true }, r2 => { sessionId = r2.sessionId; send('Page.enable'); send('Network.enable'); // Navigate to promo page send('Page.navigate', { url: TARGET_URL }); }); }); }); ws.on('message', raw => { const msg = JSON.parse(raw); if (msg.id && cbs.has(msg.id)) { const cb=cbs.get(msg.id); cbs.delete(msg.id); cb(msg.result||{}); return; } if (!msg.method) return; // Wait for the promo page to be ready if ((msg.method === 'Page.loadEventFired' || msg.method === 'Page.domContentEventFired') && !started) { // Verify we're on the right page evalStr('document.location.href', href => { console.log('Current URL after load:', href); if (href && href.includes('medios-de-pago')) { started = true; console.log('On promo page — waiting 5s for React render...'); setTimeout(extractAll, 5000); } else { console.log('Not on promo page yet, waiting for navigation...'); } }); } // Also trigger on navigation committed to the target URL if (msg.method === 'Page.frameNavigated') { const url = msg.params && msg.params.frame && msg.params.frame.url; if (url && url.includes('medios-de-pago') && !started) { started = true; console.log('Frame navigated to promo page — waiting 6s for render...'); setTimeout(extractAll, 6000); } } }); function extractAll() { // Extract card data: return as JSON string evalStr(`JSON.stringify((function(){ var btns = [].filter.call(document.querySelectorAll('button,a,span,div'), function(el){ return el.childElementCount === 0 && /ver legales/i.test(el.textContent); }); var cards = [].map.call(btns, function(btn, i){ var node = btn; for(var j=0;j<12;j++){ var p=node.parentElement; if(!p||['MAIN','BODY','SECTION','HEADER','NAV'].indexOf(p.tagName)>=0) break; var t=p.innerText||''; if(t.length>20 && t.length<3000 && t.indexOf('%')>=0) node=p; else break; } var imgs=[].map.call(node.querySelectorAll('img'),function(img){return img.alt+'|'+img.src.split('/').pop();}); return {i:i, text:(node.innerText||'').replace(/\\s+/g,' ').trim().slice(0,400), imgs:imgs}; }); return {count:btns.length, cards:cards}; })())`, val => { let data; try { data = JSON.parse(val || '{}'); } catch(e) { data = {}; } console.log('\n=== DIA PROMOS:', data.count, '==='); (data.cards||[]).forEach(c => { console.log('\n['+c.i+']', c.text); if(c.imgs&&c.imgs.length) console.log(' imgs:', c.imgs.join(', ')); }); // Click each Ver Legales let idx = 0; const total = Math.min(data.count||0, 20); function next() { if (idx >= total) { console.log('\n=== ALL LEGALS CAPTURED ==='); capturedLegals.forEach(l => console.log(l)); ws.close(); return; } const i = idx++; evalStr(`(function(){ var btns=[].filter.call(document.querySelectorAll('button,a,span,div'),function(el){ return el.childElementCount===0 && /ver legales/i.test(el.textContent); }); if(btns[${i}]){btns[${i}].click();return 'clicked';} return 'missing'; })()`, clickRes => { console.log('\n['+i+'] click:', clickRes); setTimeout(() => { // Extract modal text evalStr(`(function(){ // Check all possible modal containers var candidates = [].filter.call(document.querySelectorAll('*'), function(el){ if(!el.offsetParent) return false; var cls=(el.className||''); if(/modal|Modal|drawer|Drawer|overlay|Overlay|dialog|popup|bottom.sheet|legal|Legal|terms|Terms|lightbox/i.test(cls)) return true; if(el.getAttribute('role')==='dialog') return true; return false; }); if(candidates.length){ var text=(candidates[0].innerText||'').replace(/\\s+/g,' ').trim(); if(text.length>20) { // Try to close var c=candidates[0].querySelector('button')||candidates[0]; document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true,cancelable:true})); return 'MODAL::'+text.slice(0,500); } } // fallback: any large text block that wasn't there before return 'NONE'; })()`, modalText => { console.log(' legal:', modalText ? modalText.slice(0,150) : 'none'); if (modalText && modalText !== 'NONE') capturedLegals.push('['+i+'] '+modalText); setTimeout(next, 700); }); }, 2000); }); } next(); }); } ws.on('error', e => console.error('WS error:', e.message)); ws.on('close', () => process.exit(0)); setTimeout(() => { console.log('TIMEOUT — closing'); ws.close(); }, 120000);