简体   繁体   中英

Tampermonkey not detecting key press

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?

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");
        }
    });
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM