1

I try to replace the whole html content with the responseText returned by XMLHttpRequest, but it seems that the js in the responseText does not take effect.

here is the code:

 var newContent= evt.target.responseText;

 var newDoc = document.open("text/html", "replace");
 newDoc.write(newContent);
 newDoc.close();

ie. the js in NewConent does not run.

Is it possible to make it work? thanks.

the OS is Mac, and Browser is Chrome.

also tried Firefox in Mac, does not work either.

Update:

got it work with another round of eval.

document.body.innerHTML = responseText;
var arr = document.getElementsByTagName('script')
//run script inside div
for (var n = 0; n < arr.length; n++) eval(arr[n].innerHTML)

https://developer.mozilla.org/en-US/docs/Web/API/element.innerHTML HTML5 specifies that a tag inserted via innerHTML should not execute.

also tried the suggested solution.

var rawtext= responseText.replace(/\<\/script\>/g,'</scrxxxxxipt>' );
var fragments= rawtext.split(/xxxxx/);
var newDoc = document.open("text/html", "replace");
for (var i=0; i<fragments.length; i++)
{
        newDoc.write(fragments[i]);
}
newDoc.close();

this solution does make the plain js work. but I have some requirejs files and it does not work very well.

BTW. I find the solution based on Can scripts be inserted with innerHTML?!

2
  • Please give more context. What OS/browser? Apr 19, 2014 at 5:13
  • thanks for reminder. updated
    – echo
    Apr 19, 2014 at 5:18

1 Answer 1

3

script element end tag creates a problem for javascript parser. In this case you have to change in end tage of script elements.

this piece of code will work var newDoc = document.open("text/html", "replace"); newDoc.write("alert('dfdfd');</scr"+"ipt>");` Source: javascript embedding <script> tags in document.write not working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.