1

I am updating a div content via ajax call. The response(html) which i get contains a reference to an internal JavaScript file.

The referenced javascript is not getting loaded. How can I solved the issue.

Below is how I am setting it to a div.

 document.getElementById('content-wrapper').innerHTML = data;

The file is loaded correctly when i set the content using jQuery's .html() function. But for that we have to disable 'unsafe-eval' in our content security policy. So jQuery is not an option.

@mplungjan answers did help but i am getting below eror Error Detail

Code one
  • 83
  • 9
  • 1
    Does this answer your question? [Executing – freedomn-m Nov 12 '20 at 12:10

1 Answers1

2

Try this

const wrapper = document.getElementById('content-wrapper')
wrapper.innerHTML = data;
const scr = wrapper.querySelector("script");
const newScr = document.createElement("script");
newScr.src = scr.src;
try {
  document.head.appendChild(newScr)
} catch (e) {
  console.log("nope")
}

const data = `This is a script <script src="https://worldwide.espacenet.com/scripts/powered_by_espacenet.js"><\/script> embedded in a string`

const wrapper = document.getElementById('content-wrapper')
wrapper.innerHTML = data;
const scr = wrapper.querySelector("script");
const newScr = document.createElement("script");
newScr.src = scr.src;
console.log(newScr.src);

// this is to handle the document.write in this particular script
const myWrite = document.write;
document.write = function(str) {
  wrapper.innerHTML += str
}
try {
  document.head.appendChild(newScr)
} catch (e) {
  console.log("nope")
}
<form name=""></form>
<div id="content-wrapper"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • For more scripts: `[...wrapper.querySelectorAll("script")].forEach(script => { if (scripts.src != "") { ... }})` – mplungjan Nov 12 '20 at 13:12
  • After moving code in production i am getting error mentioned in edits.. Can you please suggest something – Code one Nov 12 '20 at 15:42
  • Nope. You are sol. Use an iframe – mplungjan Nov 12 '20 at 15:43
  • iframe is a security risk.. that's why i can't use it. – Code one Nov 12 '20 at 15:47
  • Then only solution I can think of is to include the page in html you already have. You can use a proxy if it is from a different site – mplungjan Nov 12 '20 at 16:34
  • The architecture is similar to single page application.. We do have the main layout but the certain div content needs to updated via ajax. but every content loaded does have a separate js file... – Code one Nov 12 '20 at 16:41
  • I suggest you use a server process to stitch these page together OR turn down the content policy for your site – mplungjan Nov 12 '20 at 18:04