문제

내 스크립트가 자체 헤더에 선언된 메타데이터 값을 검색할 수 있는 방법이 있습니까?아마도 API를 제외하고는 유망한 내용이 보이지 않습니다. GM_getValue().물론 여기에는 특별한 이름 구문이 포함됩니다.예를 들어 다음과 같이 시도했습니다. GM_getValue("@name").

여기서의 동기는 중복된 사양을 피하는 것입니다.

GM 메타데이터에 직접 액세스할 수 없는 경우 스크립트 자체의 본문을 읽을 수 있는 방법이 있을 수 있습니다.확실히 메모리 어딘가에 있을 것이고, 파싱하기가 그렇게 어렵지는 않을 것입니다. "// @".(내 경우에는 어떤 식으로든 필요할 수 있습니다. 왜냐하면 제가 정말로 관심 있는 값은 다음과 같습니다. @version, 이는 다음에 의해 읽혀지는 확장된 값입니다. userscripts.org.)

도움이 되었습니까?

해결책

이 답변은 오래되었습니다. Greasemonkey 0.9.16(2012년 2월)부터 다음을 참조하세요. 브록의 대답 ~에 관하여 GM_info


예.매우 간단한 예는 다음과 같습니다.

var metadata=<> 
// ==UserScript==
// @name           Reading metadata
// @namespace      http://www.afunamatata.com/greasemonkey/
// @description    Read in metadata from the header
// @version        0.9
// @include        https://stackoverflow.com/questions/104568/accessing-greasemonkey-metadata-from-within-your-script
// ==/UserScript==
</>.toString();

GM_log(metadata); 

보다 Greasemonkey-users 그룹의 이 스레드 자세한 내용은.더 강력한 구현은 끝 부분에서 찾을 수 있습니다.

다른 팁

사용 그만큼 GM_info 물체, 버전 0.9.16에서 Greasemonkey에 추가되었습니다.

예를 들어, 다음 스크립트를 실행하는 경우:

// ==UserScript==
// @name            _GM_info demo
// @namespace       Stack Overflow
// @description     Tell me more about me, me, ME!
// @include         http://stackoverflow.com/questions/*
// @version         8.8
// ==/UserScript==

unsafeWindow.console.clear ();
unsafeWindow.console.log (GM_info);


다음 객체가 출력됩니다.

{
    version:            (new String("0.9.18")),
    scriptWillUpdate:   false,
    script: {
        description:    "Tell me more about me, me, ME!",
        excludes:       [],
        includes:       ["http://stackoverflow.com/questions/*"],
        matches:        [],
        name:           "_GM_info demo",
        namespace:      "Stack Overflow",
        'run-at':       "document-end",
        unwrap:         false,
        version:        "8.8"
    },
    scriptMetaStr:      "// @name            _GM_info demo\r\n// @namespace       Stack Overflow\r\n// @description     Tell me more about me, me, ME!\r\n// @include         http://stackoverflow.com/questions/*\r\n// @version         8.8\r\n"
}

Athena의 답변을 바탕으로 각각 메타데이터 속성을 나타내는 이름/값 쌍의 개체를 생성하는 일반화된 솔루션이 있습니다.특정 속성은 여러 값(@include, @exclude, @require, @resource)을 가질 수 있으므로 내 파서는 해당 값을 배열로 캡처하거나 @resource의 경우 이름/값 쌍의 하위 개체로 캡처합니다.

var scriptMetadata = parseMetadata(.toString());

function parseMetadata(headerBlock)
{
    // split up the lines, omitting those not containing "// @"
    function isAGmParm(element) { return /\/\/ @/.test(element); }
    var lines = headerBlock.split(/[\r\n]+/).filter(isAGmParm);
    // initialize the result object with empty arrays for the enumerated properties
    var metadata = { include: [], exclude: [], require: [], resource: {} };
    for each (var line in lines)
    {
        [line, name, value] = line.match(/\/\/ @(\S+)\s*(.*)/);
        if (metadata[name] instanceof Array)
            metadata[name].push(value);
        else if (metadata[name] instanceof Object) {
            [rName, rValue] = value.split(/\s+/); // each resource is named
            metadata[name][rName] = rValue;
        }
        else
            metadata[name] = value;
    }
    return metadata;
}

// example usage
GM_log("version: " + scriptMetadata["version"]);
GM_log("res1: " + scriptMetadata["resource"]["res1"]);

이것은 내 스크립트에서 잘 작동합니다.

편집하다:Greasemonkey 0.8.0에 도입된 @resource 및 @require가 추가되었습니다.

편집하다:FF5+ 호환성, Array.filter()는 더 이상 정규식을 허용하지 않습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top