Greasemonkey不工作?

时间:2014-01-17 01:32:44

标签: javascript greasemonkey userscripts tampermonkey

所以我有以下Greasemonkey脚本:

// ==UserScript==
// @name       InstaTranslate+
// @namespace  http://use.i.E.your.homepage/
// @version    1.0.0
// @description  A browser add-on to easily translate words using the Google Translate engine.
// @include     http://*
// @copyright  2014+, Tyler Jablonski
// ==/UserScript==
function getSelectedText() {
    var text = "";
    if (typeof window.getSelection != "undefined") {
        text = window.getSelection().toString();
    } else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
        text = document.selection.createRange().text;
    }
    return text;
}

function doSomethingWithSelectedText() {
    var selectedText = getSelectedText();
    if (selectedText && event.keyCode === 81) {
                var canDo = confirm("Would you like to translate this text?");
                if (canDo==true)
                {
                var myword=selectedText;
                var urlSetUp="http://www.translate.google.com/#auto/en/";
                var urlGo=urlSetUp.concat(myword);
                window.open(urlGo);
                }
    }
    else if (event.keyCode === 81) {
            var myword=prompt("What phrase would you like to translate?");
            if (myword!=null)
            {
            var urlSetUp="http://www.translate.google.com/#auto/en/";
            var urlGo=urlSetUp.concat(myword);
            window.open(urlGo);
            }
    }
}

document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;

不幸的是,它根本不起作用。但是,当我将代码复制并粘贴到地址栏并以这种方式运行时,它工作正常。为什么这样做以及我该怎么做才能纠正它?

1 个答案:

答案 0 :(得分:0)

function doSomethingWithSelectedText()更改为function doSomethingWithSelectedText(event),或将@grant none添加到元数据块。