Reputation: 31
I am trying to create an userscript (to use with tampermonkey) which simulates pressing the Enter
button every 1 seconds.
I have tried
// ==UserScript==
// @name Userscript
// @namespace http://tampermonkey.net/
// @require https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js
// @version 0.1
// @description desc
// @author author
// @match https://example.com/*
// @grant none
// ==/UserScript==
setInterval(() =>
document.body.dispatchEvent(new KeyboardEvent("keypress", {keyCode : 13}))
, 250);
However, the keypress does not seems to works...
The body of the page contains a canvas with the id gCanvas
and multiples iframes used for ads (which are, I guess, irrelevant since I use an adblocker).
Let me know if I should add a screen of the DOM of the page from the developping tools.
E : in answer to CertainPerformance comment, I've also tried
document.getElementById('gCanvas').dispatchEvent(new KeyboardEvent("keypress", {keyCode : 13}))
without result, I also tried with keydown
and keyup
event but still without results
Upvotes: 3
Views: 1008
Reputation: 855
var elem = document.getElementById('canvas');
var ctx = elem.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 200, 200);
window.addEventListener("keydown", function(e) { console.log(e.key); }, true);
var evt = new KeyboardEvent("keydown", {key : "Enter"});
evt.keyCode = 13;
setInterval(() => {
elem.dispatchEvent(evt);
}, 1000);
<canvas id="canvas" width="200px" height="200px"></canvas>
Upvotes: 2