📜 ⬆️ ⬇️

Saving by Ctrl + S in the browser

I can be mistaken, but solutions to this problem on Habré have not yet been cited, so let me share with you a useful piece of code. Task: by pressing Ctrl + S to block the browser dialog about saving the page and run a custom function.

Problem

When editing data in forms instead of the attached “Save” button, sometimes you feel like pressing the usual Ctrl + S. This invariably leads to the appearance of a standard browser dialog that prompts you to save the current html page.

Using JavaScript, try:
* block the appearance of the dialogue on the preservation;
* catch keystrokes and start a client function, which, for example, can run ajax-submit your data;
')
To block standard event handling in a browser, use:
* The preventDefault () method of the event object. Supported in Gecko and Opera.
* The event object's returnValue property supported in IE.

Handlers are hung using the special function addHandler , so as not to change the HTML code once again. Depending on the browser, blocking is performed for the keydown event or keypress . After the save dialog is killed, you can call a suitable function.

Code


//
function addHandler(object, event, handler, useCapture) {
if (object.addEventListener) {
object.addEventListener(event, handler, useCapture ? useCapture : false);
} else if (object.attachEvent) {
object.attachEvent('on' + event, handler);
} else alert("Add handler is not supported");
}

//
var ua = navigator.userAgent.toLowerCase();
var isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1);
var isGecko = (ua.indexOf("gecko") != -1);

//
if (isIE) addHandler (document, "keydown", hotSave);
else addHandler (document, "keypress", hotSave);

function hotSave(evt) {
// event
evt = evt || window.event;
var key = evt.keyCode || evt.which;
// Ctrl+S
key = String.fromCharCode(key).toLowerCase() == "s";
if (evt.ctrlKey && key) {
//
if(evt.preventDefault) evt.preventDefault();
evt.returnValue = false;
// ,
clientFunction();
//
window.focus();
return false;
}
}
function clientFunction() {
// - ...
}


Plugin for jQuery hosted on Google Code

Using

Performance tested in:
* WIN: IE6, IE7;
* WIN: FF 1.5, NN 7.1, NN 8.0, Mozilla 1.7;
* WIN: Opera 7.1, 7.5, 8.0, 9.01, 9.2;
* MAC: They write that Mac OS X + FF3b5 works (but Ctrl + S, not Command + S);

Does not work:
* in Fox under Linux and Mac OS X when saved by Ctrl + S. For fix you need a browser patch.

The above script has been successfully tested in the Flede database editing system . The usual pressing Ctrl + S, and the base on your host received new data, and you stayed on the right page and write on :-)

If the script does not work in other browsers or platforms, write in the comments!

Crosspost Saving on Ctrl + S in the browser c webew.ru

Source: https://habr.com/ru/post/25511/


All Articles