Dynamic loading of <script>
I have a code that adds dynamic text to a page:
Code:
document.getElementById("dynamic").innerHTML = text
However, sometimes the text contains actual javascript. It seems it won't run because the page already loaded.
Can you help me add a child, etc. to get it running? The steps are:
Display the part before the script. Run the script. Display the part after the script.
For example:
Code:
text = "display this text, run this code <script>alert('foobar')</script> and then display this text."
Thanks!
You can not add script tags via innerHTML. You would have to rip out the code and run it with eval. There are libraries that automatically do this.
Eric
Alright, I've programmed the solution myself:
Code:
<span id=dynamictext>hey</span><hr>
<input type=button onclick="bla(0)" value=Button0><hr>
<input type=button onclick="bla(1)" value=Button1><hr>
<input type=button onclick="bla(2)" value=Button2>
<script>
function bla(text) {
if (text==0)
text = 'hey there'
else if (text==1)
text = 'hey <script>alert("bla")</' + 'script> yo'
else if (text==2)
text= 'hey <script>alert("bla1")</' + 'script> yo <script>alert("bla2")</' + 'script> and more'
theregex1 = new RegExp(/<script>[\s\S]+?[^<\/script>]<\/script>/ig)
if (theregex1.test(text)) {
theregex2 = new RegExp(/<script>([\s\S]+?[^<\/script>])<\/script>/i)
thematches = text.match(theregex1)
for (i=0;i<thematches.length;i++) {
thematch = theregex2.exec(thematches[i])[1]
eval(thematch)
}
text = text.replace(theregex1, "").replace(/\s\s+/, " ")
}
document.getElementById("dynamictext").innerHTML = text
}
</script>
Code:
theregex1 = new RegExp(/<script>[\s\S]+?[^<\/script>]<\/script>/ig)
if (theregex1.test(text)) {
theregex2 = new RegExp(/<script>([\s\S]+?[^<\/script>])<\/script>/i)
You don't need the new RegExp there. It makes more sense to use
Code:
theregex1 = /<script>[\s\S]+?[^<\/script>]<\/script>/ig;
if (theregex1.test(text)) {
theregex2 = /<script>([\s\S]+?[^<\/script>])<\/script>/i;
The object is useful for when you need to use a string to create the RegExp.
Great wit and madness are near allied, and fine a line their bounds divide.
Thanks. BTW, why does this only work for the first catch:
Code:
theregex = "<script>([\s\S]+?[^<\/script>])<\/script>"
theregex1 = new RegExp(theregex, "gi")
if (theregex1.test(text)) { // catches
theregex2 = new RegExp(theregex, "i") // doesn't catch
?
Thread Information
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Bookmarks