1

I need to create a new HTML page using javascript. To do that I tried using the window object

let myDocument = window;

myDocument.document.write(`
     <html>
         <head>
               <title>${title}</title>
         </head>
         <body><section id="print"></section></body>
     </html>
`)

My problem is that I would like to generate that on the background and save the result somewhere in my project.

  • The user cannot see a new page open or a new window
  • The new HTML has to be saved

These are the two problems I have at the moment. I can generate the page, but I could not find out how to do that on the background. My limitation is that the project uses pure javascript so Node.js packages might not work.

4
  • Why are you trying to do this? What's the goal? Anyhow I would personally use HTML5's offline storage Commented Aug 21, 2020 at 10:56
  • 1
    There's no need for window object in this? Why not simply store HTML in a variable? Commented Aug 21, 2020 at 10:56
  • I need to dynamically add html on it too Commented Aug 21, 2020 at 11:29
  • Document.write is no longer suitable for anything like this - Chrome, and possibly webkit browsers in general - does not create a new execution context for the page written with document.write so JavaScript written into the document risks generating errors because you've used the same variable name previously. Commented Aug 21, 2020 at 11:50

1 Answer 1

1

Instead of document.write you can save it in a variable & use it when you want or save it through service or localStorage.

You code must be like:

const title = "Hello World!";
let myDocument =
     `<html>
         <head>
               <title>${title}</title>
         </head>
         <body><section id="print"></section></body>
     </html>`;
     
console.log(myDocument);

Sign up to request clarification or add additional context in comments.

1 Comment

That will solve at least three problems... The actual and two I would have in the future. So simple and I didn't see it, thanks a lot!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.