Reading Content Globals: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
mNo edit summary
remove obsolete content
 
Line 1: Line 1:
Described here is a straightforward and reliable way to read values from the content page's global scope.
The technique [http://wiki.greasespot.net/index.php?title=Reading_Content_Globals&oldid=5610 previously described] at this page is no longer necessary.
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).
Read [[Content Script Injection]] for an easier replacement technique.
 
See the snippet at userscripts.org: http://userscripts.org/scripts/show/85398
 
== Example ==
 
This script:
 
<pre>
// ==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);
</pre>
 
Run on a page like:
 
<pre>
<html>
<head>
<script type="text/javascript">
var secret1 = 42;
var secret2 = 17;
</script>
</head>
<body>
Page with globally scoped javascript values.
</body>
</html>
</pre>
 
The console will display:
 
<pre>
got global named secret1 with value 42
got global named secret2 with value 17
</pre>


[[Category:Coding Tips:Interacting With The Page]]
[[Category:Coding Tips:Interacting With The Page]]
[[Category:@require Library]]

Latest revision as of 15:55, 23 September 2015

The technique previously described at this page is no longer necessary. Read Content Script Injection for an easier replacement technique.