2014-07-08 2 views
4

나는 GM_getValue undefined error을 보았지만, GM_getValueGM_setValue을 부여하고 기본값을 정의했습니다.GM_getValue가 정의되지 않았습니다 (삽입 코드에서)?

예제 코드 : 당신이 바로 위의 예를 설치 한 후 SO에 "대답을 추가"텍스트 영역을 클릭하면

// ==UserScript== 
// @name  SO_test 
// @include  https://stackoverflow.com/* 
// @version  1 
// @grant  GM_getValue 
// @grant  GM_setValue 
// ==/UserScript== 

// Get jQuery thanks to this SO post: 
// https://stackoverflow.com/a/3550261/2730823 
function addJQuery(callback) { 
    var script = document.createElement("script"); 
    script.setAttribute("src", "//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"); 
    script.addEventListener('load', function() { 
     var script = document.createElement("script"); 
     script.textContent = "window.jQ=jQuery.noConflict(true);(" + callback.toString() + ")();"; 
     document.body.appendChild(script); 
    }, false); 
    document.body.appendChild(script); 
} 

function main() { 
$("#wmd-input").on("contextmenu", function(e) { 
    e.preventDefault(); 
    console.log("GM_getValue: " + GM_getValue("extra_markdown", True)); 
}); 
} 
addJQuery(main); 

, FF는 콘솔에 GM_getValue is undefined을 말한다. 왜 이런거야?

GM 기능을 작동 시키려면 어떻게해야합니까?

답변

8

해당 스크립트는 대상 페이지 범위 (삽입 된 코드) 내에서 GM_getValue()을 실행하려고합니다. this is not allowed. GM_ 기능을 활용
How to use GM_xmlhttpRequest in Injected Code?
또는
How to call Greasemonkey's GM_ functions from code that must run in the target page scope?
: 코드가 정말 주입해야하는 경우
는에서 기술을 사용합니다.

이 스크립트는 더 이상 쓸모없고 위험한 방법으로 jQuery를 추가하고 있습니다. 그런 일은하지 마라. 최악의 경우 this optimized, cross-platform method (second example)을 사용하십시오. 그러나 Greasemonkey (또는 Tampermonkey)를 사용하고 있기 때문에 다음과 같이 스크립트를 만들 수 있습니다. 훨씬 간단하고 안전하며 빠르며 효율적입니다.

// ==UserScript== 
// @name SO_test 
// @include https://stackoverflow.com/* 
// @version 1 
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js 
// @grant GM_getValue 
// @grant GM_setValue 
// ==/UserScript== 

$("#wmd-input").on ("contextmenu", function (e) { 
    e.preventDefault(); 

    //-- Important: note the comma and the correct case for `true`. 
    console.log ("GM_getValue: ", GM_getValue ("extra_markdown", true)); 
}); 
관련 문제