Reading Content Globals

From GreaseSpot Wiki
Revision as of 15:49, 4 September 2010 by Arantius (talk | contribs)
Jump to navigationJump to search

Described here is a straightforward and reliable way to read values from the content page's global scope. It relies on asynchronously passing messages via events (available in Firefox 3.0 and higher), and native JSON support (available in Firefox 3.5 and higher).

See the snippet at userscripts.org: http://userscripts.org/scripts/show/85398

Example

This script:

// ==UserScript==
// @name           Global Reader
// @include        *
// @require        http://userscripts.org/scripts/source/85398.user.js
// ==/UserScript==

function got(name, value) {
  console.log('got global named', name, 'with value', value);
}
read_content_global('secret1', got);
read_content_global('secret2', got);

Run on a page like:

<html>
<head>
<script type="text/javascript">
var secret1 = 42;
var secret2 = 17;
</script>
</head>
<body>
Page with globally scoped javascript values.
</body>
</html>

The console will display:

got global named secret1 with value 42
got global named secret2 with value 17