Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a nice way to tell jQuery to not eval scripts on ajax requests that are HTML

I'm using jQuery to make an ajax request, and everything is working as expected. But it's evaluating the scripts in the wrong context.

I have an iframe (same domain, no worries here), and I'm trying to get the scripts to eval in the context of the iframe, instead of where the ajax request was made -- eg. a different frame.

I figured I could tell ajax not to eval the scripts, and I would do the work myself to eval them in the right context. Any ideas, or ways to disabled the automatic eval?

Edit

So, I was somewhat wrong about the initial question.. The scripts are not evaluated when loaded, but rather when the content is being placed in the document. You can see this by testing the example:

$('#some_element').html('<span>content</span><script>alert(window)</script>');

Now, when doing this from a different frame, the evaluation happens in the scope of where you're calling, not the element you're inserting content into.

I ended up setting the content without using jQuery, and then finding/evaling any script tags:

element.get(0).innerHTML = data;
element.find('script').each(function() {
  otherWindow.eval(this.innerText);
});

Final Update

I ended up tracking it down to the source, and overriding it from there.. the following is coffeescript, but you can get the idea. I chose to override it because for my usage, this should never happen in the top window, but is expected in the iframe content.

    $.globalEval = (data) -> (iframeWindow.execScript || (data) -> iframeWindow["eval"].call(iframeWindow, data))(data) if (data && /\S/.test(data))
like image 717
jejacks0n Avatar asked Nov 14 '22 21:11

jejacks0n


1 Answers

This questions shows how to do custom eval of the scripts:

jQuery: Evaluate script in ajax response

In the following piece of code... ** this code is from the answer of the other question ** just got it as a snippet:

  $("body").append($(xml).find("html-to-insert").eq(0));
  eval($(xml).find("script").text());

eval itself is bound to a window, that you can define to be the context:

windowObject.eval - when calling just eval('...'), it supposes you are calling just like this: window.eval('...')

Now you need to get the window that corresponds to the frame you want to execute the eval in and do something like this:

myIFrameWindow.eval('...')

When you do this, it is execute in the context of that window. It is just a matter of finding the window associated with the iframe that you want now.

To find the window of a given frame, take a look at this post:

Getting IFRAME Window (And Then Document) References With contentWindow

like image 156
Miguel Angelo Avatar answered Dec 22 '22 05:12

Miguel Angelo