1

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...

2 Answers 2

2

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.

1
  • Thanks for clarifying this Tim. I think I came up with an equivalent bit of code to do the same thing. Commented Oct 15, 2012 at 13:50
0

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));
}());

You must log in to answer this question.

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