简体   繁体   中英

Crossbrowser CTRL+S JavaScript problems

I see this is very popular question, but i still cannot find right solution.

I'm trying to call function (save) on Ctrl + s pressed inside my textarea. I found that Chrome or IE needs "keydown" and FireFox needs "keypress".

Actually, Firefox registers "keydown" - calls my "alert" but don't prevent browser "Save As" dialog.

I tried to put both events, - then FireFox prevents Save As dialog, but calls my Alert twice.

Here's code:

$("#mytextarea").on("keypress keydown",function(e) { 
    if ((e.which == '115' || e.which == '83' ) && (e.ctrlKey || e.metaKey)) {
         e.preventDefault();
         alert("Ctrl-s pressed");
         return false;
    }
    return true;
});

JS fiddle - try to open with FF

Does anyone have real crossbrowser solution?

For a save browser compatibility you can also use one of the the following javascript libraries:

with jquery for example:

I found hint that looks like working solution at: Can't override ctrl+s in Firefox using jQuery Hotkeys

it looks like i should wrap function in setTimeout... it works for now.

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