orshachar
orshachar

Reputation: 5037

get <script> content as String

I tried using Javascript on demand to override cross domain problems.

So now I have something like that on my page:

<script id="scr1" src="{some other domain url}"></script>

The content of this script is a simply an array:

["hello", "world", "what", "where"]

I want to somehow get this content as string so I can eval it.
I wish I had some JS/JQuery method like

var v = eval($("#scr1").getContent());

Can you help me please?

Note: I can't use ajax as a solution.

Upvotes: 4

Views: 11137

Answers (3)

Miere
Miere

Reputation: 1595

So here is my contribution if someone really needs to find a way to read every script content.


  jQuery("script").each(function(){
    var scriptContent = this.innerText
    // do something with scriptContent
  })

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532445

You should look up JSONP. What you want your script to return is the invocation of a callback with the data as the argument.

<script id="scr1" src="http://www.example.com/some/action?callback=cb" type="text/javascript></script>

The server side then, would produce the script contents:

cb( ["hello", "world", "what", "where"] );

Then on in your page, you'd need to have a function named cb that expects an array.

function cb(data) {
  // do something with the array
}

Of course, this expects the cooperation of the server to understand your callback parameter and respond appropriately. If you control the server, that's pretty easy to do. If not, then you'll need to use an API that is constructed to return JSONP. The callback parameter is a pretty standard name for such frameworks. If they don't have an API, then you need to proxy the request on your server, in which case you can use standard JSON.

FWIW, jQuery makes this pretty easy for APIs that expect to return JSONP.

$.getJSON( 'http://example.com/api/method?callback=?', data, function(result) {
     // do something with the json result
});

You can also use this with post/get/ajax methods as well, but getJSON is easier. Note that including the callback parameter automatically tells it to use a JSONP (script) request and automatically fills in the name of the callback it creates to wrap the (anonymous) callback function in the request.

Upvotes: 9

Paul Creasey
Paul Creasey

Reputation: 28824

should be possible with jquery.getScript

$.getScript('urlOfRemoveScript',function(script){
    var v = eval(script);
});

Not 100% sure this will work though.

Upvotes: 2

Related Questions