TroutMan
TroutMan

Reputation: 23

Use a different variable for each domain in a Greasemonkey script

I have a Greasemonkey script that saves a list of numeric IDs as a delimited string using GM_setValue(). The script uses this list to filter out items on a bulletin board.

I'm trying to figure out the best way to make this script work for multiple domains, so each domain has its own list of IDs. As it stands now, if I filter out ID "12345" on one site, it will also be filtered on every other site.

I realize I could append the domain to each ID and search for a combination of ID + domain, but I'd prefer to save space unless it's my only choice. Ideally I'd have a separate variable for each domain.

Upvotes: 2

Views: 734

Answers (1)

Brock Adams
Brock Adams

Reputation: 93633

You can use location.hostname to get the domain and then generate a key for use with GM_setValue and GM_getValue. After that, the rest of your code is the same.

For example:

// ==UserScript==
// @name     _Store and retrieve a comman var that's unique to each domain
// @include  http://DOMAIN_1.COM/YOUR_PATH/*
// @include  http://DOMAIN_2.COM/YOUR_PATH/*
// @include  http://DOMAIN_3.COM/YOUR_PATH/*
// @grant    GM_getValue
// @grant    GM_setValue
// ==/UserScript==
var storageKey  = "IDs_" + location.hostname;
var idList      = GM_getValue (storageKey, "");

console.log ("This site's list was: ", idList);

idList         += ",7";

GM_setValue (storageKey, idList);


This keeps a separate idList for each domain you visit (That matches the @include, @match, and @exclude directives).

Upvotes: 1

Related Questions