sjv
sjv

Reputation: 9

Triggering Ctrl S via button in js

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

Upvotes: 0

Views: 3511

Answers (4)

Daniel Cooke
Daniel Cooke

Reputation: 1634

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.

Upvotes: 0

Aditya Bhave
Aditya Bhave

Reputation: 1028

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">

Upvotes: 1

Pedram
Pedram

Reputation: 16615

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

Upvotes: 0

Lars Gross
Lars Gross

Reputation: 110

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

Upvotes: 0

Related Questions