Reading Content Globals: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
(Created page with 'Described here is a straightforward and reliable way to read values from the content page's global scope. It relies on asynchronously [https://developer.mozilla.org/en/DOM/window…')
 
mNo edit summary
Line 1: Line 1:
Described here is a straightforward and reliable way to read values from the content page's global scope.
Described here is a straightforward and reliable way to read values from the content page's global scope.
It relies on asynchronously [https://developer.mozilla.org/en/DOM/window.postMessage passing messages] via events (available in Firefox 3.0 and higher), and [https://developer.mozilla.org/en/Using_native_JSON native JSON support] (available in Firefox 3.5 and higher).
It relies on asynchronously [https://developer.mozilla.org/en/DOM/window.postMessage passing messages] via events (available in Firefox 3.0 and higher), and [https://developer.mozilla.org/en/Using_native_JSON native JSON support] (available in Firefox 3.5 and higher).
See the snippet at userscripts.org: http://userscripts.org/scripts/show/85398


== Example ==
== Example ==

Revision as of 15:49, 4 September 2010

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