0

我为 Greasemonkey/Tampermonkey 编写了一个供个人使用的用户脚本,它应该自动登录某些页面。为此,它会查找提交按钮并事先检查是否已插入凭据。到目前为止,这有效。但是,脚本会时不时地停止,仅当在浏览器中执行单击或击键时才会继续运行。我首先想到了某种安全功能,但这并不能完全解释为什么它有时会起作用。我该如何解决?由于它可能是浏览器问题,我正在使用 Vivaldi (Chromium) 和 Tampermonkey。

// ==UserScript==
...
// @grant        none
// @run-at       document-start
// ==/UserScript==


function getSafe(fn) {
    try {
        if (fn !== null) { return fn(); }
    } catch (e) {
        console.log("selector error");
        return null;
    }
}
function saveClick(button) {
    if (button !== null) {
        // some click tries
        button.focus()
        button.click();
        setTimeout(function() { button.click() }, 300)
        document.querySelector("body").click();
        return true;
    }
}

function main() {
    var interval = setInterval(function() {
        const input = document.getElementsByTagName("input");
        if (input.length > 0) {
            clearInterval(interval);
            Array.from(input).forEach((itm) => {
                itm.addEventListener('input', event => {
                    // Service example
                    {
                        let button = getSafe(() => document.evaluate('//button[contains(text(),"Login")]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0));
                        if (saveClick(button)) { return }
                    }
                });
            });
        }
    },100);
}

document.addEventListener("DOMContentLoaded", main);

4

0 回答 0