Run script tags loaded with ajax

2019-06-28 01:05发布

General Question

Say you have a simple ajax request like $("#container").load('/url #content');. The loaded DOM will be something like

<a>email</a>
<script>/* some script */</script>

What can I do to get the contents of the script tags to execute?

Specific Question

Cloudflare automatically protects email addresses in the DOM by replacing the text with [email protected] and including a script that unravels it. However, the contents can be loaded asynchronously and the script that does the unraveling won't be executed. I could just turn off the email protection feature (I think) but I'm wondering if there's another way around this.

Example

See it in action at http://aysites.com/what -- click "Contact"

3条回答
一夜七次
2楼-- · 2019-06-28 01:39

My answer includes some of Tooraj's magic as well.

Basically, we're going to use the same load function, and in the callback, we're going to grab the script, take the functions from within it, then eval them.

$("#container").load('/url #content', function(){
  eval($('#container script').html()); 
});

using the above selector and grabbing the HTML out of that selector (which happens to be the functions in the script), we can then eval that function and have it run.

Here's a working jsFiddle.

查看更多
Bombasti
3楼-- · 2019-06-28 01:48

you could put the script part alone in a page with appropriate headers and then use $.getScript() to get and execute the script,

See Doc: http://api.jquery.com/jQuery.getScript/

查看更多
smile是对你的礼貌
4楼-- · 2019-06-28 01:53

There is a pure js function which invokes the JavaScript compiler. It's eval. You need to use it.

Examples:

jQuery.globalEval("var newVar = true;")

on jQuery.com

Or

eval("x=10;y=20;document.write(x*y)");
document.write("<br />" + eval("2+2"));
document.write("<br />" + eval(x+17));

on w3schools

查看更多
登录 后发表回答