简体   繁体   中英

Javascript redirect to dynamically created HTML

I have a javascript routine that dynamically creates an HTML page, complete with it's own head and script tags.

If I take the contents of the string and save it to a file, and view the file in a browser, all is well, but if I try document.write(newHTML), it doesn't behave the same. The javascript in the header of the dynamic newHTML is quite complicated, and I cannot include it here... But please believe me that it works great if I save it to a file, but not if I try to replace the current page with it using document.write. What possible pitfalls could be contributing to this that I'm not considering? Do I possibly need to delete the existing script tags in the existing header first? Do I need to manually re-call onLoad??

Again, it works great when the string is saved to, for example, 'sample.html' and browsed to, but if I set var Samp="[REAL HTML HERE]"; and then say document.write(Samp); document.close(); the javascript routines are not executing correctly.

Any hints as to what I could be missing?

Is there another/better way to dynamically replace the content of the page, other than document.write?

Could I somehow redirect to the new page despite the fact that doesn't exist on disk or on a server, but is only in a string in memory? I would hate to have to upload the entire file to my server simply to re-download again it to view it.

How can I, using javascript, replace the current content of the current page with entirely new content including complex client-side javascripting, dynamically, and always get exactly the same result as if I saved the string to the server as an html file and redirected to it?

How can I 'redirect' to an HTML file that only exists as a client-side string?

Maybe eval() function would help here? It's hard to give ansver without seeing the code.

You can do this:

var win=window.open("") //open new window and write to it

var html = generate_html();

win.document.write(html)
win.document.close();

Never tried this, but i think it should be possible. Some thoughts on what might make it work:

  • Make sure the document containing your js is sent with the correct headers / mimetype / doctype
  • Serve the javascript in a valid way, for example by sending a w3c valid page containing the script tag.

Maybe then it works. If not, try to erase the current html before writing the new one.

Also, it might be helpful to look how others managed to accomplish this task. If i remind it correctly, the google page is also essentially a short html page with a bunch of js.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM