0

I wanna use my browser's save as function. How can i trigger CTRL+S via button in javascript. Is it possible ? i have tried this

$("#Save").click(function() {
    var e = $.Event( "keydown", { keyCode: 115, ctrlKey:true} );
    $("body").trigger(e);
});
Dharman
  • 30,962
  • 25
  • 85
  • 135
sjv
  • 9
  • 1
  • 2
  • This has been answered [here](https://stackoverflow.com/a/93836/11719787) – Sameer Jan 27 '20 at 12:22
  • 2
    Does this answer your question? [Best cross-browser method to capture CTRL+S with JQuery?](https://stackoverflow.com/questions/93695/best-cross-browser-method-to-capture-ctrls-with-jquery) – johannchopin Jan 27 '20 at 12:34
  • 1
    @sjv is not asking how to determine if `Ctrl + S` has been pressed, but asking if it is possible to Trigger it. – Daniel Cooke Jan 27 '20 at 13:28
  • If you want to trigger the "Save As" dialog by custom events then it is not allowed due to security reasons. – Aditya Bhave Jan 27 '20 at 13:32

4 Answers4

1

You can generate a custom event using KeyboardEvent. But default action associated with the event (e.g. ctrl+s, ctrl+p) is not initiated by the browser. Take a look at following note from MDN

Source - https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

Note: Manually firing an event does not generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.

Code to fire custom event:

(() => {
  document.querySelector("#saveMe").addEventListener('click', ($event) => {

    let event = new KeyboardEvent('keydown', {
      key: "s",
      code: "KeyS",
      ctrlKey: true
    });

    document.dispatchEvent(event);
  });

  document.addEventListener('keydown', ($event) => {
    console.log('keydown fired', $event);
  });

})();
<input type="button" id="saveMe" value="Save Me">
Aditya Bhave
  • 998
  • 1
  • 5
  • 10
0

Only with jQuery, Import it to your File.

$(document).bind('keydown', function(e) {
  if(e.ctrlKey && (e.which == 83)) {
    e.preventDefault();
    alert('Ctrl+S');
    return false;
  }
});
Lars Gross
  • 102
  • 6
0

CTRL+S

You can simulate ctrl+s on click event like below example:

$("#Save").click(function() {
  e = $.Event("keydown");
  e.which = 83; // S
  e.ctrlKey = true; // CTRL
  $(document).trigger(e);
});
Pedram
  • 15,766
  • 10
  • 44
  • 73
0

This is not possible as far as I can tell. For security reasons, it would not be sensible for browsers to allow Javascript to trigger events that interact with the browser like that.

However there is an experimental FileSystemAPI you could use.

You could create your own modal-popup, and use the FileSystemAPI to read local files, and prompt the user to select a save location.

Daniel Cooke
  • 1,426
  • 12
  • 22