Execute js in html loaded page with sencha.

Update : scroll for part 2 !

Part 1 : evil eval trick

Ok. So I load html in a sencha panel like this :

Ext.Ajax.request({
  url:'mypage.html',
  success:function(response, options) {
    Ext.getCmp('myPanel').update(response.responseText, true);
  },
  failure:function(response, options) {
    // Redirect to success for status == 0 for local files
    if (response.responseText && response.status == 0) this.success(response, options);
  }
});

Oh dear. I don’t know another way to load a local file except redirecting to success if the response status is 0. Sorry about that.

Next trick is : how to execute some JS inside this loaded html page. Because it doesn’t work. At all.

You’ll hate me about this, but in my local html file :

function logize() {
  console.log('pouet');
}

This function is defined in a <script type=”text/javascript” id=”executeMe”>…</script> tag.

Then, in the success function, I added :

eval($('#executeMe').text());
logize();

Tricky trick is tricky ! I know eval is evil…

Any idea on how to do it nicely ?

Part 2 : nice way

Yep. The end of the eval reign has come.

I change a little bit of my html file :

(function() {
  function logize() {
    console.log('pouet');
  }
  logize();
})();

In my sencha success function :

var code = $('#executeMe').text();
var codefunc = new Function(code);
codefunc();

So :

  • No eval function
  • No need to rely on a global function called in sencha’s success function
  • Nice closure in the html ;)

That’s done !

Leave a Reply

Your email address will not be published. Required fields are marked *

*