title: How to simulate a keypress in a Greasemonkey script?
body: <p>I have found lots of info online about how to use the <code>initEvent</code> and <a href="https://developer.mozilla.org/en-US/docs/DOM/element.dispatchEvent" rel="nofollow"><code>dispatchEvent</code> functions</a>, but I can't for the life of me get them to work in practice.  </p>
  
  <p>I'm trying to get a script to press the <kbd>Enter</kbd> key every 5 seconds. My userscript code (minus irrelevant metadata) is below:</p>
  
  <pre><code>// ==UserScript==
  // @namespace      http://userscripts.org/scripts/show/153134
  // @require        https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js
  //
  // @grant          unsafeWindow
  //
  // ==/UserScript==
  
  $(function(){
  window.setInterval(function(){
      var ev = document.createEvent("KeyboardEvent");
      ev.initKeyEvent("keypress", true, false, window, 0, 0, 0, 0, 13, 13);
          window.dispatchEvent(evt);
  }, 5000);
  });
  </code></pre>
  
  <p>Checkout my script on userscript to see how poorly it works (add a user include domain and test it on any <code>&lt;textarea&gt;</code>).  Is Greasemonkey just not letting it through, or do I need to do something differently?</p>