1

New greasemonkey user, I have put together this code to check a box name isRegex... but the check box code is skipped

console.log("Monkey script");
var chkBox,regBox;
var sQuery = "//input[@type='checkbox']"
chkBox = document.evaluate(sQuery, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for ( var i = 0; i < chkBox.snapshotLength; i++){
    regBox = chkBox.snapshotItem(i);
    if (regBox.name == "isRegex" && regBox.checked == false){
        regBox.checked = true;
    }
}
console.log("Done");

chkBox.snapshotLength looks like a method, but all documentation I have seen uses it this way. I have tried, chkBox.snapshotLength() but nothing. Pointer please?


  • tried to add a wait till the page loads?
window.addEventListener('load', function() {
    var chkBox = document.getElementsByName('isRegex');
    const clickEvent = document.createEvent('MouseEvents');
    clickEvent.initEvent('click', false, true);
    chkBox.dispatchEvent(clickEvent);
    console.log(chkBox);
}, false);
console.log("Done");

Error:

Paused on exception
TypeError: chkBox.dispatchEvent is not a function
1
  • Do you have a reason to not use document.querySelectorAll? I'd advise trying that. You might also need to use MutationObserver to watch for new checkboxes being added in case the form you're trying to affect is loaded after the page load. Or - a lazy solution - setInterval with 800ms interval and keep trying until you find the checkbox. Commented Feb 20, 2024 at 11:34

1 Answer 1

0

Could you please specify what it is exactly you're trying to accomplish? You try to toggle that checkbox on/off?

If so then try the following:

window.addEventListener('load', () => {
    var checkbox = document.querySelector('input[name="isRegex"]');
    checkbox.click()
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.