Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override Ctrl + N in firefox to launch AJAX

Note: Juan Mendes answer is the selected answer because it had the most useful response to my situation. Though AxGryndr also had some useful information. Read both answers and they are both good for different situations. Thank you both for helping with this.

I already asked a similar question about this here which did solve the first part of my problem now I have another. I want the Ctrl + N to launch a script that contains an AJAX but once I run the .get function it cause the default to launch. Does anyone know a work around for this.

This fiddle has some code that shows my problem. Here is some of the code.

function checkkey(e)
{
    if(e.ctrlKey && e.keyCode == 'N'.charCodeAt(0) && !e.shiftKey && !e.altKey)
    {
        try{e.preventDefault();}catch(ex){}
        var m_objXMLHttpReqObj = new XMLHttpRequest();
        m_objXMLHttpReqObj.open("GET", "", false);
        m_objXMLHttpReqObj.send();
    }
}

JSFIDDLE

like image 312
wolfcall Avatar asked Apr 15 '13 17:04

wolfcall


1 Answers

Your code was not preventing the default behavior

function checkkey(e) {
    if(e.ctrlKey && e.keyCode == 'N'.charCodeAt(0) && !e.shiftKey && !e.altKey) {
        e.preventDefault();
        // Now send your AJAX

It also seems that AJAX is interfering with the ability to stop the default behavior. You were trying to send a synchronous AJAX request (don't ever do that, it will halt the browser) and you weren't giving it a URL to go to (triggering an error). As soon as you change your settings to properly give it a URL and to make it asynchronous, then it does work in FF.

Here's the working code

function checkkey(e) {
    if(e.ctrlKey && e.keyCode == 'N'.charCodeAt(0) && !e.shiftKey && !e.altKey){
        e.preventDefault();
        var m_objXMLHttpReqObj = new XMLHttpRequest();
        m_objXMLHttpReqObj.open("GET", 
                // URL to go to
                "/echo/html/", 
                // Asynchronous
                true);
        m_objXMLHttpReqObj.send("");
    }
}

However, in Chrome (it may not be of use to you, but to others who read this answer), if you add a console.log at the top of your handler, you'll see that the handler never gets. Therefore, Chrome doesn't even let you see the CTRL+N combination and you can't do anything about it. Just like Windows applications don't get notified of CTRL+ALT+DEL

If the application has to work for multiple browsers, my suggestion is to use a different combination like ALT+SHIFT+N, you really don't want to take over the basic browser shortcuts.

like image 196
Juan Mendes Avatar answered Sep 20 '22 06:09

Juan Mendes