Greasemonkey 名称空间的用途是什么?

我正在学习如何使用 Greasemonkey,并且想知道 @namespace元数据 id 是用来做什么的。

它必须是一个网址吗? 或者它可以是一个文件夹/目录在我的计算机上?

还需要填吗?

39339 次浏览

A namespace is used to avoid naming collisions. If you called your script foobar and someone else did as well, then central repositories would have a hard time telling them apart.

Therefore you should provide some URL that you control (i.e. you own it or can administrate it) that basically means "everything with that URL is by me". Now those central repositories can distinguish between foobar from http://somesite.com/ and foobar from http://anothersite.com.

It's not necessary for basic operation, but strongly suggested if you want to share your scripts.

Keep in mind that mailto:someone@example.com is also a valid URL and might be a possible option when you don't own or control a domain of your own.

In general, a namespace is an abstract container providing context for the items (names, or technical terms, or words) it holds and allowing disambiguation of items having the same name (residing in different namespaces).

Source: Namespace - Wikipedia

And more specific:

This is a URL, and Greasemonkey uses it to distinguish user scripts that have the same name but are written by different authors. If you have a domain name, you can use it (or a subdirectory) as your namespace. Otherwise you can use a tag: URI.

@namespace is optional. If present, it may appear only once. If not present, it defaults to the domain from which the user downloaded the user script.

Source: Dive Into Greasemonkey - Metadata

One place you can see the practical effect of namespaces is in storing preferences. Nampsaces are used to uniquely identify scripts for any script-specific stored preferences.

For example, if you have a script like this:

// ==UserScript==
// @name            Script Name
// @namespace       http://example.com
// @include         *
// ==/UserScript==




GM_setValue("key", "value");

That would be stored in your preferences (accessible in prefs.js, and about:config) like so:

greasemonkey.scriptvals.http://example.com/Script Name.key

Note the format: greasemonkey.scriptvals . namespace . scriptname . key/variablename

Namespace can be a URL, but not only. You can use as namespace some words as your username or real name.