Adding a custom keyboard shortcut using userscript to Chrome with Tampermonkey

こ雲淡風輕ζ 提交于 2019-12-04 08:29:17
Brock Adams

That code does not work in a userscript because it is calling javascript functions defined by the target page. Userscripts operate in various sandboxes, and so cannot see the target page's JS so easily.

Tampermonkey (and Greasemonkey) provide a way around this with unsafeWindow. (Plain Chrome userscripts do not support unsafeWindow in any useful way.)

So, to use those functions, prefix them like so:

// ==UserScript==
// @name       ChartGame
// @namespace  http://www.chartgame.com/
// @version    0.1
// @description  enter something useful
// @match      http://www.chartgame.com/play*
// @copyright  2012+, You
// ==/UserScript==
function doc_keyUp(e) {
    switch (e.keyCode) {
        case 49:
            //1
            unsafeWindow.mon_clk(3);
            break;
        case 50:
            unsafeWindow.mon_clk(6);
            break;
        case 83:
            //s
            unsafeWindow.BuySell(0);
            break;
        case 68:
            //d
            unsafeWindow.BuySell(1);
            break;
        case 70:
            //f
            unsafeWindow.TimelapseDwn();
            unsafeWindow.TimelapseUp();
            break;
        default:
            break;
    }
}
document.addEventListener('keyup', doc_keyUp, false);


An alternative approach, and one that works on plain Chrome userscripts, is to Inject your code. But since you are using Tampermonkey, just use the unsafeWindow approach in this case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!