This whole thing started out as a nice-to-have. I have a blog (you’re reading it). I have a URL shortener (jmbk.nl). They are separate apps on separate domains. When I publish a post here, I diligently create the short URL for it manually in order to publish that short URL on social sites (the URL shortener has some minimalist stats associated with each short URL; so minimal, it’s only a count of the number of times it was used). Yeah, I know, silly, huh: why can’t each post generate its own short URL?
Now I could have done this in C# and .NET as a plug-in to the blogging software I use, but where’s the fun in that? Let’s do it in JavaScript!
What I want is some code that will get the URL of a blog post when that post is displayed in the browser (easy!), call my URL shortener service with it via good-old AJAX, and receive the short URL as a reply. The big issue about this simple plan is the so-called “Same-Origin Policy”. In essence, getting data from the same site (that is, protocol, domain/host, and port number) via JavaScript is smiled upon, but getting data from another site entirely is frowned upon to the point it doesn’t work. Since my pages are on boyet.com/, I can only get data from boyet.com/. It’s all to do with maintaining strict security boundaries (think of cookies as a big example).
Nevertheless, sometimes it might be advantageous for your code to get some data from another site. An example might be to display the top ten most recent of your tweets from Twitter in your blog webpage. The problem here is that twitter.com is not the domain of your personal blog, so what can be done?
If you think about it, the one thing you can get from other sites is JavaScript code inside script elements. Here as an example is how this site gets jQuery:
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.9.1.min.js">script>
When the browser encounters a script element likes this, two things happen: first, the JavaScript file referenced by that URL is downloaded (via HTTP GET), and second, the script thus downloaded is executed. Hmm.
Let’s continue this thought experiment. These days we get our data in the JSON format; that is, code that defines a JavaScript object. Here’s an example of a JSON object that is relevant to my discussion:
{
"shortURL": "http://jmbk.nl/j6Q2K",
"requestCount": 42
}
Running before I can walk, I could construct the source URL I need in a
Loading links to posts on similar topics...
No Responses
Feel free to add a comment...
Leave a response
Note: some MarkDown is allowed, but HTML is not. Expand to show what's available.
_emphasis_**strong**[text](url)`IEnumerable`* an item1. an item> Now is the time...Preview of response