Javascript chrome 扩展没有用 click() 点击按钮

Javascript chrome extension not clicking button with click()

我想使用 chrome 扩展来自动控制网站。 例如,它应该单击一个按钮。 这是我的代码:

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();

所以我的猜测是我在 utilities.js 文件中遗漏了一些东西。 奇怪的是,如果我例如尝试 .click() 按钮,我会去改变它工作的按钮的样式。例如将它的背景更改为粉红色:

activityTab.style['background'] = "#FF00FF"

当我尝试单击它而不是将其添加到 document.get... 时,我还尝试访问 activityTab 数组的 [2]: activityTab[2].click() 但这也没有用。

为什么不执行 .click()

问题和@wOxxOm 猜的一样! 下面的代码为我修复了它:

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);
    }
}