skip to Main Content

This question was asked a lot, but I cant find a solution for my problem…

script.js

    $(document).ready(function ()
    {
    
        if (document.getElementById('searchSerialButton') !== null)
        {
            document.getElementById("searchSerialButton").addEventListener('click', () =>
            {
                console.log("scripts.js -> ready() callback -> addEventListener(`click`) callback");
            });
        }
    
    });

index.html

    <!DOCTYPE html>
    <html lang="en">
    
        <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>check guarantee card </title>
            <link rel="stylesheet" href="style.css">
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
            <script src="/scripts.js"></script>
        </head>
    
        <body>
            <div>
                <h1>Enter product serial number into search field</h1>
                <input id="serialInput"/>
                <button id="searchSerialButton">Check</button>
            </div>
        </body>
    
    </html>

I have Tampermonkey script and I wish it to fill serial input field and then PRESS the button. Example: I open the URL "http://127.0.0.1:5500/index.html?serial=12345678"

The Tampermonkey script grabs serial from URL (12345678), insert it into serialInput field and has to press Check button, but the button is not pressed. The click() is not working. If we check the console log, we could see, that when we press ENTER inside serial input field, check_btn.click() working, but when we just call it from tampermonkey, it will not click the button.

Is there a way to PRESS the Search button in this case?

// ==UserScript==  
// @name         Test press button  
// @namespace    http://tampermonkey.net/  
// @version      0.1  
// @description  try to take over the world!  
// @author       You  
// @match        http://127.0.0.1:5500/index.html?serial=*  
// @icon         https://www.google.com/s2/favicons?sz=64&domain=0.1  
// @grant        none  
// ==/UserScript==  
  
(function ()  
{  
    'use strict';  
    // DOMContentLoaded fires before TamperMonkey starts running on the page  
    // fix error "Uncaught TypeError: element is null"  
    if (document.readyState == "complete" || document.readyState == "loaded" || document.readyState == "interactive")  
    {  
        const params = new URLSearchParams(window.location.search);  
        const inputField = document.getElementById("serialInput");  
        inputField.value = params.get("serial");  
        console.log(`serial = document.getElementById("serial") = `, inputField);  
        const check_btn = document.getElementById("searchSerialButton");  
        console.log(`check_btn = document.getElementById("searchSerialButton") = `, check_btn);  
        check_btn.click(); // DOES NOT WORK!  
  
        // Execute a function when the user presses a key on the keyboard  
        inputField.addEventListener("keydown", function (event)  
        {  
            // If the user presses the "Enter" key on the keyboard  
            if (event.code === "NumpadEnter" || event.code === "Enter")  
            {  
                // Cancel the default action, if needed  
                event.preventDefault();  
                // Trigger the button element with a click  
                check_btn.click(); // WORKS!  
            }  
        });  
  
    }  
})();

2

Answers


  1. Chosen as BEST ANSWER

    It seems, that the problem was with not all elements were generated. So I added the function:

     function Submit() {
         document.querySelector("#searchSerialButton").click()
    }
    

    and changed document.querySelector("#searchSerialButton").click() with it like that:

    const check_btn = document.getElementById("searchSerialButton");
    setTimeout(function() {check_btn.click()}, 0);
    

  2. Since the problem seems to be that your script is running too early, there are a number of approaches to solving this problem. As the OP has already noted in their answer, adding a delay is one solution.

    Setting @run-at

    Try changing the @run-at meta property.

    // @run-at document-idle
    

    Which changes when your userscript runs.

    The script will run after the page and all resources (images, style sheets, etc.) are loaded and page scripts have run.
    

    Tampermonkey Docs

    window.onload

    Alternatively, if you prefer a Javascript solution you could run your script inside the callback of the load window event. See MDN docs for more.

    window.onload = (event) => {
      // Run your script here
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search