onkeydown适用于某些网站,有些网站也没有

时间:2016-01-16 10:58:28

标签: javascript greasemonkey tampermonkey

我正在尝试为gmail设置一些键盘快捷键。我使用tampermonkey和onkeydown函数。我发现gmail是一个特殊的网站,因为我发现在许多网站上这种方法有效,但不适用于gmail。我尝试了这3个选项,但都没有用。你有什么建议?

   // @match        https://mail.google.com // ALL HAVE THIS LINE

选项1

    document.onkeydown = keydown;
    function keydown(evt){
              console.log("hhwhehehheeheh");
    }

选项2

    document.documentElement.onkeydown = keydown;
    function keydown(evt){
              console.log("hhwhehehheeheh");
    }

选项3

document.body.focus();
    document.documentElement.onkeydown = keydown;
    function keydown(evt){
              console.log("hhwhehehheeheh");
    }

1 个答案:

答案 0 :(得分:1)

您的选项1是正确的,问题是模式:// @match https://mail.google.com

请改用以下模式:// @match https://mail.google.com/*

您的模式的问题是只适用于没有路径的https://mail.google.com,但是从gmail开始,内容不会从https://mail.google.com提供,因此它始终使用包含https://mail.google.com/mail/...之类路径的位置,因此您必须在模式中添加*才能加载脚本。

使用第二个@match和你的脚本很适合我:

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://mail.google.com/*
// @grant        none
// ==/UserScript==
/* jshint -W097 */
'use strict';

document.onkeydown = keydown;
function keydown(evt){
    console.log("hhwhehehheeheh");
}

有关详细信息,请参阅@match

希望它有所帮助,