I would like to use a chrome extension to automatically control a website. For example it should click a button. This is my code:
manifest.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>"]
}
popup.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>
popup.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);
utilities.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();
So my guess is that there is something I miss in the utilities.js file.
Strange thing is that if I for example instad of trying to .click()
the button, I would go and change the style of the button it works. For example changing the background of it to pink like that:
activityTab.style['background'] = "#FF00FF"
I also tried to access [2] of the activityTab array when I try to click it instead of adding it to the document.get...
like that:
activityTab[2].click()
But this also didn't work.
Why is it not performing the .click()
?
CodePudding user response:
Problem was as guessed by @wOxxOm ! This code below fixed it for me:
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);
}
}