3

I'm writing a Tampermonkey code for a webpage like ConverTo:
It's supposed to automatically select the second option in a dropdown:

<select class="format-select">
    <option value="mp3">MP3</option>
    <option value="mp4">MP4 (video)</option>
</select>

, several seconds after the page is fully loaded.
But nothing happens.

My code:

......
// @match      https://www.converto.io/*
// @require    http://code.jquery.com/jquery-1.11.0.min.js
// ==/UserScript==

$(document).ready(function(){
setTimout(test(),10000); 
function test() 
{ 
    $(".format-select").val('mp4'); 
}
})();

Please help!

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
user2650501
  • 119
  • 4
  • 11

1 Answers1

5

See Choosing and activating the right controls on an AJAX-driven site.
Many AJAX-driven controls cannot just be changed; they also must receive key events, for the page to set the desired state.

In the ConverTo case, that select appears to expect :

  1. A click event.
  2. A value change.
  3. A change event.

You would send that sequence with code like this complete, working script:

// ==UserScript==
// @name     _ConverTo, Automatically select mp4
// @match    https://www.converto.io/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

waitForKeyElements (".format-select:has(option[value=mp4])", selectFinickyDropdown);

function selectFinickyDropdown (jNode) {
    var evt = new Event ("click");
    jNode[0].dispatchEvent (evt);

    jNode.val('mp4');

    evt = new Event ("change");
    jNode[0].dispatchEvent (evt);
}

There are other state sequences possible, to the same end.

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • Works perfect and thanks a lot, sir. Now I want to let it click the following "CONVERT" button, but I never learned anything about ajax, so I could only give it a random try mimicking your code --- waitForKeyElements (".btn lg btn-default convert-btn",....... { var evt = new Event ("click"); jNode[0].dispatchEvent (evt);} It doesn't work. Any idea? – user2650501 Jan 02 '17 at 14:09
  • That's not how Stack Overflow works. You get 1 question, per question. And follow-up questions, in the comments, should not "move the goalposts". Don't be a [Help Vampire](http://meta.stackoverflow.com/a/258279/331508). ... [Accept this answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235); then upvote it; then ask your additional question as a new question. BUT, be warned that the 1st link, in the answer, already shows how to chain control activations. Read and attempt to apply that linked answer before asking again. – Brock Adams Jan 02 '17 at 19:40
  • Thank you for the answer, works like a charm! You're the best :) – Overloard Apr 28 '20 at 19:55