Skip to main content
1 of 5
brasofilo
  • 1k
  • 8
  • 22

How to use the StackExchange object on a userscript?

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?

brasofilo
  • 1k
  • 8
  • 22