tomcritchlow
tomcritchlow

Reputation: 785

What is this window["obvInit"] ({...}) doing in a script?

I'm attempting to extract some information from Medium URLs and I notice that each page has the entire post contents stored in JSON format. The content looks like this on the page:

<script>// <![CDATA[
window["obvInit"]({"value":{"id":"e389ba1d8f57","versionId":"1b74...

How do I easily extract this JSON from the page? What does the preface of window["obvInit"] before the JSON mean? Can I call the function obvInit in my Chrome console and get the JSON output somehow?

Upvotes: 1

Views: 186

Answers (2)

rvighne
rvighne

Reputation: 21917

This is a technique known as JSONP. Basically, since some older browsers don't have great support for cross-origin AJAX using XMLHttpRequest, you can insert a <script> tag into the page that gets the resource you want, except wrapped like this:

functionName({ /* ...data... */ });

So it calls a function known as functionName with the data as an argument. You would provide this function in your own code before inserting that script, like so:

function functionName(data) {
    // use the data
}

window["obvInit"]() is equivalent to window.obvInit() which is equivalent to calling a function defined as obvInit at the global level.

As scripts are not subject to the same-origin policy, you can now get JSON-like data from any domain that will return it in this format.

Upvotes: 1

t.animal
t.animal

Reputation: 3331

What this does is call a function. It's probably (but not necesarrily) been declared like function obvInit(...){...} on the global window namespace. Now for your problem: You can easily extract the passed object by overwriting the function like this:

var _oldObvInit = window.obvInit;
window.obvInit = function(){
        console.log(arguments[0]); //use this to extract the object
        console.log(JSON.stringify(arguments[0])); //use this to extract JSON
        return _oldObvInit.apply(window, arguments);
}

Put this before the script tag you've posted here and after the declaration of the function obvInit.

A bit context: inside every javascript function there's an implicit variable arguments which stores the arguments to the function as an array. And apply calls a function, sets the context (this) and takes the arguments as an array. Exactly what you need to wrap it.

Upvotes: 2

Related Questions