у меня есть расширение для google на JS manifest { "manifestversion": 3, "name": "Info…
- User
у меня есть расширение для google на JS
manifest { "manifest_version": 3, "name": "Info Extractor", "version": "1.0", "action": { "default_popup": "popup.html", "default_icon": "icons/icon128.png" }, "permissions": ["activeTab", "scripting"], "background": { "service_worker": "background.js" } }
background function updateData() { chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { if (tabs.length === 0) return; // Нет активной вкладки
chrome.scripting.executeScript({ target: { tabId: tabs[0].id }, func: () => { document.querySelectorAll('.by-table-row').forEach((row) => { const cells = row.querySelectorAll('.by-table-cell'); const orderPriceCell = cells[8]; if (cells[5].innerText === 'Купить' && cells[11]) { orderPriceCell.innerText = cells[11].innerText; // Ставим "Цену предложения" } else if (cells[5].innerText === 'Продать' && cells[7]) { orderPriceCell.innerText = cells[7].innerText; // Ставим "Цену спроса" } }); }, }); }); }
// Запускаем обновление данных каждую секунду setInterval(updateData, 500);
popup
Отправить в книгу ордеров. Click Original Button Введите новое значение Обновить значение popup document.getElementById('fetchButton').addEventListener('click', () => { chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { chrome.scripting.executeScript({ target: { tabId: tabs[0].id }, func: () => { console.log('Скрипт начал выполняться');
// Получаем все строки таблицы const rows = Array.from(document.querySelectorAll('.by-table-row')); let positions = []; // Пропускаем первые две строки rows.forEach((row, index) => { if (index < 2) return; const cells = row.querySelectorAll('.by-table-cell'); const orderPriceIV = cells[8]?.innerText.trim(); const direction = cells[5]?.innerText.trim(); const quantityCell = cells[9]; // Ссылка на DOM элемент для quantity const quantity = parseFloat(quantityCell.innerText.trim()) || 0; const askSize = parseFloat(cells[10]?.innerText.trim(), 10) || 0; const bidSize = parseFloat(cells[6]?.innerText.trim(), 10) || 0; if (orderPriceIV && direction) { let position = { orderPriceIV, direction, quantity, quantityCell, // Сохраняем ссылку на DOM элемент askSize, bidSize, }; positions.push(position); } }); console.log('Собранные позиции:', positions); // Функция для изменения количества по минимальному коэффициенту const scaleAllQuantities = (positions) => { let scaleFactors = []; // Группируем позиции по цене ордера const groupedByOrderPrice = positions.reduce((acc, position) => { if (!acc[position.orderPriceIV]) { acc[position.orderPriceIV] = []; } acc[position.orderPriceIV].push(position); return acc; }, {}); Object.keys(groupedByOrderPrice).forEach((orderPrice) => { const group = groupedByOrderPrice[orderPrice]; console.log(`Группа для цены ${orderPrice}:`, group); const buyGroup = group.filter(pos => pos.direction === 'Купить'); const sellGroup = group.filter(pos => pos.direction === 'Продать'); // Вычисляем коэффициенты масштабирования для каждой группы if (buyGroup.length > 0) { const totalAskSize = buyGroup[0].askSize; // Предполагаем одинаковый размер аска для всех в группе const totalQuantity = buyGroup.reduce((sum, pos) => sum + pos.quantity, 0); if (totalQuantity > totalAskSize) { scaleFactors.push(totalAskSize / totalQuantity); } } if (sellGroup.length > 0) { const totalBidSize = sellGroup[0].bidSize; // Предполагаем одинаковый размер бида для всех в группе const totalQuantity = sellGroup.reduce((sum, pos) => sum + pos.quantity, 0); if (totalQuantity > totalBidSize) { scaleFactors.push(totalBidSize / totalQuantity); } } }); // Находим минимальный коэффициент масштабирования const minScaleFactor = Math.min(...scaleFactors, 1); console.log(`Минимальный коэффициент масштабирования: ${minScaleFactor * 100}%`); // Применяем минимальный коэффициент масштабирования ко всем позициям positions.forEach(pos => { const newQuantity = pos.quantity * minScaleFactor; pos.quantity = newQuantity; pos.quantityCell.innerText = newQuantity.toFixed(2); // Обновляем текст элемента на странице }); return minScaleFactor < 1; }; // Вызов функции scaleAllQuantities и контроль выполнения let requiredScaling = scaleAllQuantities(positions); if (!requiredScaling) { console.log('Все условия выполнены, продолжаем выполнение скрипта.'); const firstButton = document.querySelector('.by-button.by-builder-opr-btn.by-button--contained.by-button--xx-large.by-button--brand'); if (firstButton) { firstButton.click(); setTimeout(() => { const secondButton = document.querySelector('.by-button.by-dialog__btn.by-button--contained.by-button--xx-large.by-button--brand'); if (secondButton) { secondButton.click(); } else { console.log('Вторая кнопка не найдена'); } }, 1000); } else { console.log('Первая кнопка не найдена'); } } else { console.log('Количество в позициях было изменено для соответствия доступным размерам.'); // Выполнить программу, нажатие кнопок const firstButton = document.querySelector('.by-button.by-builder-opr-btn.by-button--contained.by-button--xx-large.by-button--brand'); if (firstButton) { firstButton.click(); setTimeout(() => { const secondButton = document.querySelector('.by-button.by-dialog__btn.by-button--contained.by-button--xx-large.by-button--brand'); if (secondButton) { secondButton.click(); } else { console.log('Вторая кнопка не найдена'); } }, 1000); } else { console.log('Первая кнопка не найдена'); } } - Assistant
- User
напиши весь код после изменений
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.