Skip to content

Instantly share code, notes, and snippets.

@insin
Created March 25, 2011 14:05
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save insin/886877 to your computer and use it in GitHub Desktop.
Save insin/886877 to your computer and use it in GitHub Desktop.
Chrome Extension compatibility for Greasemonkey's GM_getValue and GM_setValue
<html>
<script>
chrome.extension.onRequest.addListener(function(request, sender, sendResponse)
{
if (request.type == "getprefs")
{
var response = {};
for (var i = 0, l = localStorage.length; i < l; i++)
{
var key = localStorage.key(i);
response[key] = localStorage.getItem(key);
}
sendResponse(response);
}
else if (request.type == "setpref")
{
localStorage.setItem(request.name, request.value);
}
});
</script>
</html>
// Request settings from the extension's localStorage and kick things off
chrome.extension.sendRequest({type: "getprefs"}, function(response)
{
cachedSettings = response;
init();
});
{
...
"background_page": "background.html",
"content_scripts": [
{
"js": ["UserScript.js", "ChromeContentScript.js"],
"run_at": "document_end"
}
],
...
}
var isGM = !(typeof GM_getValue === "undefined" || GM_getValue("a", "b") === undefined);
/**
* If we're running on a content page, this variable will point at an object
* containing settings retrieved from the extension's localStorage, otherwise
* we're running in the extension's context and want to access localStorage
* directly.
*
* This allows us to include this script for use as a library in extension
* contexts, such as in a prefs page.
*/
var cachedSettings = null;
if (!isGM)
{
GM_getValue = function(name, defaultValue)
{
var value = (cachedSettings === null ?
localStorage.getItem(name) :
cachedSettings[name]);
if (value === undefined)
{
return defaultValue;
}
var type = value[0],
value.substring(1);
switch (type)
{
case "b":
return (value === "true");
case "n":
return Number(value);
default:
return value;
}
}
GM_setValue = function(name, value)
{
value = (typeof value)[0] + value;
if (cachedSettings === null)
{
localStorage.setItem(name, value);
}
else
{
cachedSettings[name] = value;
chrome.extension.sendRequest({type: "setpref", name: name, value: value});
}
}
}
function init()
{
// Do your thing
}
// Chrome will use another content script to initialise the script.
if (isGM)
{
init();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment