0

I am trying to write a code to bind the save as option on click event.I don't want to use filesaver.js. I want pure javascript to write this code.

Poles
  • 3,585
  • 9
  • 43
  • 91
  • 1
    http://stackoverflow.com/questions/93695/best-cross-browser-method-to-capture-ctrls-with-jquery – Vivek Jan 06 '14 at 11:32
  • yes, it is possible and lots of apps do it... unfortunately they don't support command+s for mac users :P – ddoor Jan 06 '14 at 11:35
  • 1
    @Vivek As far as I can tell this question is asking the opposite of the ones you linked - not how to capture ctrl+s keyboard events, but to trigger ctrl+s/save-as commands by methods _other_ than keyboard/app-menu methods – Brian North Jan 06 '14 at 11:37

2 Answers2

1

HTML5 standards introduced the File API, which should allow scripts to offer up "files" (Blobs) for users to save. Support is shoddy, though, which is why polyfills like FileSaver.js exist. Filesaver.js is "pure" javascript, too, so I'm not sure why needing a pure javascript solution precludes its use (unless you mean you can't load outside scripts - just minify and inline it (along with licence, etc.)) Right now, if you must code it yourself, any cross-browser solution you come up with is likely to be an effective rewrite of the polyfil.

Once you have an implementation of saveAs(), simply attach it to whatever event trigger you like:

myButton.addEventListener( 'click', function() { window.saveAs( fileBlob, 'filename.txt' ) } );

Clarification: As per the W3C spec on Events, all untrusted events (includes key-press events) act as if event.preventDefault() was called - so there is explicitly no way to simulate an actual ctrl+s keypress - only ways to simulate its effects.

ale
  • 6,369
  • 7
  • 55
  • 65
Brian North
  • 1,398
  • 1
  • 14
  • 19
0

You could do something like this:

var isCtrlPressed = false;

function onKeyDown(event) {
    if (event.keyCode == 17) { // Control got pressed
        isCtrlPressed = true;
    }
    if (event.keyCode == 83) { // "s" got pressed
        // if control is pressed too execute some code
        if (isCtrlPressed) {
            // Your code here
        }
    }
}

function onKeyUp(event) {
    if (event.keyCode == 17) { // Control got pressed
        isCtrlPressed = false;
    }
}

Then on your body tag add the following events:

<body onkeydown="onKeyDown(event)" onkeyup="onKeyUp(event)">
</body>

You can find a lifedemo here: http://jsbin.com/eBIRAfA/1/edit

RononDex
  • 4,143
  • 22
  • 39
  • I think this is the wrong way around. On a mouse event, these key events should be emitted and not the other way around. – Christoph Jan 06 '14 at 12:06