Skip to content
Advertisement

Tampermonkey automation of selecting option in a menu

I’m trying to write a script for selecting an option from a menu once the website is loaded. Here is the code of the menu.

<select name="abc" id="abc" multiple="" size="3">
    <option value="0">A</option>
    <option value="1">B</option>
    <option value="2">C</option>
    <option value="3">D</option>
    <option value="4">E</option>
</select>

I have tried several codes from StackOverflow. Like

document.getElementById('abc').value = '1';

and

document.getElementById("abc").selectedIndex = '1';

Both of them work in the Console of Google Chrome. However, it does not work when I copy and paste the script in tampermonkey. Does anyone have any idea about this problem?

Edited

Here is the full script.

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        This is my link
// @icon         https://www.google.com/s2/favicons?sz=64&domain=edu.hk
// @grant        none
// ==/UserScript==

document.getElementById('abc').value = '1';

Advertisement

Answer

Try this:

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @match        This is my link
// @icon         https://www.google.com/s2/favicons?sz=64&domain=edu.hk
// @grant        none
// ==/UserScript==

setTimeout(() => {
    document.getElementById('abc').value = '1';
},1500);

Perhaps the JavaScript is running before those elements have been created on the page…? The suggested code waits 1.5 seconds before trying to change the value. If that works, change the 1500 to 300 or 500 or ?.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement