Home > Software design >  Tampermonkey not detecting key press
Tampermonkey not detecting key press

Time:04-25

I am trying to execute this code in a webpage, which will alert "shift" if it detects a shift key pressed.

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        ...
// @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @require      http://code.jquery.com/jquery-3.4.1.min.js
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    alert('Loaded!');


    var $ = window.jQuery;
    $(document).keypress(function(e) {
        if (e.which == 16) {
            alert("shift");
        }
    });

})();

The program alerts "Loaded!" but doesn't alert "shift" when I press the shift button. Can anyone please help me figure out where the problem is?

CodePudding user response:

The keypress event has been deprecated. Use the keydown event instead.

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://stackoverflow.com/*
// @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @require      http://code.jquery.com/jquery-3.4.1.min.js
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    alert('Loaded!');
    var $ = window.jQuery;
    $(document).on('keydown', function(e) {
        if (e.which == 16) {
            alert("shift");
        }
    });
})();
  • Related