Take the 2-minute tour ×
Stack Apps is a question and answer site for apps, scripts, and development with the Stack Exchange API. It's 100% free, no registration required.

Most APIs take a parameter site which must be set to the name of the site your queries are about.

For meta.travel or travel.

But of course sites have various names, for example gaming.stackexchange.com is also called arquade. Various of these can be dug out of the page HTML in various ways.

But is there an official way to get the name in the format required by the API from the HTML or DOM?

This is important when making a userscript or browser extension that should work on all Stack Exchange sites. Including a lookup table in your code is brittle and will need to be updated every time new sites appear.

When testing the API there is an autocomplete field for which site, but a Greasemonkey script etc doesn't have access to such a list of sites.

Does the site JavaScript initialize a variable for us? (MediaWiki does it this way) Or is there some field in the page I should extract with jQuery etc that contains the API-friendly site name?

Or is it always guaranteed to be the same as in the page URL? If so then we can just use window.location.hostname and remove the .com from the end.

Actually that might be a bit too simple. At least the "big three" sites plus Stackapps will work but all the others I can think of also need the .stackexchange removed...

share|improve this question

2 Answers 2

up vote 2 down vote accepted

You can actually just pass in window.location.hostname directly:

This parameter can be the full domain name (ie. "stackoverflow.com"), or a short form identified by api_site_parameter on the site object.

(emphasis mine)

Since the site does not provide the short form to you directly anywhere, going the full hostname route is probably your best bet.

/^((?:meta\.)?(?:[^.]+))\./.exec(window.location.hostname)[1]

should also reliably get you the short form, but it seems like a less clean approach.

share|improve this answer
    
Thanks for clarifying this Tim. I think I came up with an equivalent bit of code to do the same thing. –  hippietrail Oct 15 '12 at 13:50

While Tim's answer was coming in and my interconnection was temporarily interrupted I wrote this function which I think is equivalent:

(function(){
  var h = window.location.hostname;

  return h.substring(0, h.length - (h.indexOf('stackexchange.com') === -1 ? 4: 18));
}());
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .