Hi I am working on a little project I'd like to call post database and I got a little problem. when user clicks a page number, I bring html content from server and add it to page. And I can see the new content on the page. But if new html content has some java script it does not run.
you can see the example on

go to tutorials page, and click page 3 . new page will come. including following alert inside

alert('asdf');

But it show alert window. Somehow browser does not fire javascripts.
Here is my guess: it does not work because you can not use javascript to shape pages after page load.(I just made that up. but there is no other logical explanation I can come up with.)

Dani AI

Generated

Browsers will not reliably execute <script> tags when they are simply injected via innerHTML, and calling document.write after the page has finished loading will overwrite the document (the browser implicitly reopens the document). That explains why the alert or other script code seen in the injected HTML doesn't run. 's eval tip can work for small inline snippets but is risky and doesn't solve document.write behavior. was on the right track creating <script> elements dynamically, but script.innerText can be unreliable across browsers — use a text node or the text property instead.

A robust pattern is:

  • Parse the incoming HTML into a temporary container.
  • Remove and collect all <script> elements (preserve order).
  • Move non-script nodes into the target container.
  • For each collected script: if it has a src, create a new <script> element and append it; if it is inline, create a script node with a text node (fallback to .text for older browsers) and append it so the engine executes it.

Example utility (safe cross-browser way to run inline script strings):

function runInline(code) {
  var s = document.createElement('script');
  s.type = 'text/javascript';
  try { s.appendChild(document.createTextNode(code)); }
  catch (e) { s.text = code; } // IE fallback
  document.head.appendChild(s);
}

To handle third‑party code that uses document.write, temporarily override document.write so its output is inserted into the intended container instead of the main document, then restore it:

var oldWrite = document.write;
try {
  document.write = function(html) {
    targetContainer.insertAdjacentHTML('beforeend', html);
  };
  runInline(thirdPartyCode);
} finally {
  document.write = oldWrite;
}

Cautions: executing remote or untrusted HTML/scripts is a serious XSS risk — sanitize inputs. For external scripts that must execute in order, load them sequentially (chain onload callbacks or use Promises) because dynamically appended src scripts can load asynchronously. Overall, remove reliance on document.write when possible and use DOM methods to insert and execute scripts reliably.

Recommended Answers

All 4 Replies

Hi, you have to add an Id to the script

<script type="text/javascript" id="evalMe">
        alert('asdf');
	pdbinit(23001);
</script>

and when the dynamic content is load you have to find the script getElementById('evalMe') and apply eval.

:-)

First of all thank you for quick response.

Let me tell you what I am trying to this project. I go to settings page and create a new wall. then in my page (in this case tutorial page 3). than I call pdbinit function. which writes two div elements with document.write() and then fill inside divs with the data it gets from server. now here is the problem. if I use eval ,I wont be able to use document.write because My text will already be converted to elements and added to htmldom. so what I need is to use document.write in the text of innerhtml.

I simplified the question here is the code.

<html>
<head>
	<script type="text/javascript">
	function inject(targetDiv){
		var content = '<b>This is the text before script</b> <script type="text/javascript">document.write("<br>This part is written via script")</script';
		content +='>';//I am adding this here to broke </script!> tag
		targetDiv.innerHTML = content;}
	</script>
</head>
<body>
<div id="myDiv"></div><br>
<input type="button" value="inject HTML" onclick="inject(document.getElementById('myDiv'))"/>
<input type="button" value="Call Document.write after page load" onclick="document.write('Calling document.write after page load')"/>
</body>
</html>

Here I have a button when I click it , I inject an html (including some script) into the page. but script does not run. how can I run this. I also added a button to run document.write. if you press it it will run document.write. which will overwrite the content of the page. this has to be called by browser only when browser convert text to htmldom elements. (I am just guessing right now.)

Try this one:

<html>
<head>
<script type="text/javascript">
<!--

var inject = function( targetDiv ) {
   targetDiv.innerHTML = "";

   var content = "<b>This is the text before script</b>\n";
   var script = document.createElement("script");
   script.type = "text/javascript";
   script.id = "script1";
   script.innerText = "function injectFunc() { document.write( '<br>This part is written via dynamic injected script!' ); }";
   targetDiv.appendChild( script );
   targetDiv.innerHTML += content;
};
//-->
</script>
</head>
<body>
<div id="myDiv"></div><br>
<input type="button" value="inject HTML" onclick="inject(document.getElementById('myDiv'))"/>
<input type="button" value="Call Dynamic Function" onclick="injectFunc();" />
</body>
</html>

actualy that did not work either.I tried it on windows (ff , ie , chrome). It worked as same as before. and there is another problem. innerText of new script element looks empty from firebug. I suspect that innerText property is read only.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.