Me gustaría usar una extensión de Chrome para controlar automáticamente un sitio web. Por ejemplo, debe hacer clic en un botón. Este es mi código:
manifiesto.json:
{ "manifest_version": 2, "name": "FTB", "description": "my extension", "version": "1.0", "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" }, "permissions": ["tabs", "<all_urls>"] }ventana emergente.html:
<!DOCTYPE html> <html> <head> <title>Fill</title> </head> <body> <h2 id="htwo">Button presser</h2> <button id="press">Go to activity tab</button> <script src="popup.js"></script> </body> </html>emergente.js
function injectTheScript() { // Gets all tabs that have the specified properties, or all tabs if no properties are specified (in our case we choose current active tab) chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { // Injects JavaScript code into a page chrome.tabs.executeScript(tabs[0].id, { file: 'utilities.js' }); }); } // adding listener to your button in popup window document.getElementById('press').addEventListener('click', injectTheScript);utilidades.js
/** * Gets the desired element on the client page and clicks on it */ function goToActivityTab() { var activityTab = document.getElementsByClassName('ut-tab-bar-item')[2]; activityTab.click(); } goToActivityTab(); Así que supongo que hay algo que extraño en el archivo utilities.js. Lo extraño es que si, por ejemplo, en lugar de intentar hacer .click() en el botón, iría y cambiaría el estilo del botón que funciona. Por ejemplo, cambiando el fondo a rosa así:
activityTab.style['background'] = "#FF00FF" También traté de acceder a [2] de la matriz de la ficha de actividad cuando intento hacer clic en ella en lugar de agregarla al document.get... así: activityTab[2].click() Pero esto tampoco funcionó.
¿Por qué no está realizando el .click() ?
¡El problema fue adivinado por @wOxxOm! Este código a continuación lo arregló para mí:
function mouseEventClick() { const transferWindowNavBtn = document.querySelector('body > main > section > nav > button.ut-tab-bar-item.icon-transfer'); if (transferWindowNavBtn) { //--- Simulate a natural mouse-click sequence. triggerMouseEvent(transferWindowNavBtn, 'mouseover'); triggerMouseEvent(transferWindowNavBtn, 'mousedown'); triggerMouseEvent(transferWindowNavBtn, 'mouseup'); triggerMouseEvent(transferWindowNavBtn, 'click'); } else console.log('ERROR: Transfer Window not visible!'); function triggerMouseEvent(node, eventType) { const clickEvent = document.createEvent('MouseEvents'); clickEvent.initEvent(eventType, true, true); node.dispatchEvent(clickEvent); } }