This object seems to be available in all Stack Exchange pages and contains interesting information about the actual page, site, user, among others. Just type StackExchange
on the console to check it out.
For example, with StackExchange.options.locale
I can detect if the site is pt.stackoverflow (yes, here location.hostname
would be the same), and with StackExchange.options.user.isRegistered
if the user is logged or not.
Here, a simplified script:
// ==UserScript==
// @name (SE) Inspect global object
// @match *://*.stackoverflow.com/*
// @grant none
// ==/UserScript==
var start_up = function( $ ) {
// Run only on individual posts
if( ( StackExchange.options.routeName.indexOf('Questions/Show') === -1 ) )
return;
/* do our thing */
};
function with_jquery( f ) {
var script = document.createElement("script");
script.type = "text/javascript";
script.textContent = "(" + f.toString() + ")(jQuery)";
document.body.appendChild(script);
};
with_jquery( start_up );
In Chrome, the object is recognized at root level, side by side with with_jquery
, but in Firefox it only works inside the start_up
. Brock Adams mentions that the object may not be available when the script fires. Can we somewhat rely on that object? Could @run-at document-end
help here?
In a related note, I've seen a couple of scripts that deal with Comments failing in some circumstances. In this one I added a setTimeout
and it finally prevented the error to occur. But that got me thinking that maybe it's beneficial that we detect that StackExchange ended its initialization before firing any action, similar to this crazy AJAX detection that the omnipresent Brock does :)
I think a TL;DR would be, I'm trying to make this work in Tamper and Grease:
if( ( StackExchange.options.routeName.indexOf('Questions/Show') === -1 ) )
with_jquery( start_up );
else
with_jquery( something_else );