Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

html - Replacing Entire Page Including Head Using Javascript

I have a Javascript function that is passed a string. The string that it is passed is an entire webpage, including the header. I need the Javascript to replace the entire current page, head and all with the new content.

Consider the following HTML file:

<html>
  <head>
    <script language="Javascript">
      <!--
      var newContent='<html><head><script language="Javascript">function Hi() {alert("Goodbye World");}</script></head><body onload="Hi();">New Content</body></html>';
      function ReplaceContent(NC) {
        document.body.innerHTML=NC;
      }
      function Hi() {
        alert("Hello World");
        ReplaceContent(newContent);
      }
      -->
    </script>
  </head>
  <body onload="Hi();">
    Original Content
  </body>
</html>

In this case, the passed string is:

<html><head><script language="Javascript">function Hi() {alert("Goodbye World");}</script></head><body onload="Hi();">New Content</body></html>

But of course, since the "ReplaceContent" function is only replacing the body, but not the header, I never get the "Goodbye World" alert.

Ignoring "why I would want to do this", How can I dynamically replace the entire page, including the header, and javascript functions?

Please remember the "source" html ('newContent' above) exists only as a string, it does not exist on a server anywhere, so I cannot just redirect to it.

What changes I make to "ReplaceContent" above to cause the "Goodbye World" alert to appear once the content is replaced? Please keep in mind I cannot know in advance the value of the newContent variable!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use document.write.

<html>
  <head>
    <script language="Javascript">
      <!--
      var newContent='<html><head><script language="Javascript">function Hi() {alert("Goodbye World");}</script></head><body onload="Hi();">New Content</body></html>';
      function ReplaceContent(NC) {
        document.open();
        document.write(NC);
        document.close();
      }
      function Hi() {
        ReplaceContent(newContent);
      }
      -->
    </script>
  </head>
  <body>
    Original Content
    <a href="javascript:Hi()">Replace</a>
  </body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...