How can I use GreaseMonkey to give the browser back the "/" key?

dotjs, greasemonkey, javascript

Solution

If you set `addEventListener()`Doc on `window` and use "event capture", you will catch 99% of what the page tries to do. (Not counting plugins like Flash)

You can't be sure if the page fires off of `keydown`, `keyup`, `keypress`, or some combination, so intercept `keydown` (the typical event used) and `keyup`. But, if the page fires off of `keypress`, then blocking the event may require this kind of technique. This is because the `keypress` event, on `<body>`, bubbles up to trigger Firefox's in-page search, but there is no way to (re)trigger that search from javascript (for security).

Fortunately, your two sample sites do not require any drastic measures.

Event constants, like `DOM_VK_SLASH` are great, but they are still pretty much Firefox-only. From this question's tags (dotjs), it is not clear if you mean for this to work on Chrome, too.

Putting it all together, this complete script works:

// ==UserScript==
// @name        _Nuke the forward slash on select pages
// @include     https://github.com/*
// @include     https://wiki.jenkins-ci.org/*
// @grant       GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/

//-- "true" tells the listener to use capture mode.
window.addEventListener ('keydown',  blockSlashKey, true);
window.addEventListener ('keyup',    blockSlashKey, true);
/*-- Don't block keypress on window or body, this blocks the default
    page-search, too.
window.addEventListener ('keypress', blockSlashKey, true);
*/

function blockSlashKey (zEvent) {
    var FORWARD_SLASH   = 191;  // For keydown and keyup
    var ASCII_SLASH     = 47;   // For keypress

    if (    zEvent.which === FORWARD_SLASH
        || (zEvent.which === ASCII_SLASH  &&  zEvent.type == "keypress")
    ) {
        zEvent.stopPropagation();
    }
}

Note: This script seems to work well on the two sites you listed, in both Chrome and Firefox. And, it will not stop the typing of / into inputs or textareas. But, there is a tiny chance that it might cause some sites to not fire other events on the / key.

If that happens, then use checks like `zEvent.target.nodeName == "BODY"` to restrict `blockSlashKey()`'s operation.

Problem

Lots of web pages seem to use the / key for searching. I'd like to disable that because 100% of the time I want to use / to search in the page in FireFox. Is there a way I can override this behavior with GreaseMonkey or dotjs? The best public example of this is https://www.github.com/, also https://wiki.jenkins-ci.org/display/JENKINS/Issue+Tracking

Original source

Related problems