Solution 1 :

If it is a page you want to download, why not use a link with the download attribute?

Else you can use the Filereader API

Solution 2 :

Try like below:

<a 
  download 
  href="https://stackoverflow.com/questions/69040140/get-current-web-pages-innerhtml-and-download-it-as-html-file-using-javascriptv" 
/>

you just need to replace your button tag to a tag, and define a varible in your component to replace the value pass to href.

Problem :

I have web application which is in vue framework. I have to send web page URL as an input and get the innerHTML of that page and download that as a html file by clicking download file.

I have written the vue component and adding the codesandbox sample.

<template>
  <input type="url" v-model="urlPath" />
   <button class="download_button" @click="downloadHtml">Download HTML</button>
</template>

methods

    methods: {
     downloadHtml() {
     let url = this.urlInput;
      fetch(url)
        .then((res) => res.text())
        .then((html) => this.downloadAsFile("report.txt", html));
   },   
   downloadAsFile(name, text) {
  const link = this.createDownloadableLink(name, text);
  const clickEvent = new MouseEvent('click');
  link.dispatchEvent(clickEvent);
},

createDownloadableLink(fileName, content) {
  let link = document.createElement("a");
  link.download = fileName;
  link.href = `data:application/octet-stream,${content}`;
  return link;
}
    }

Here is the Codesandbox example
Sandbox Link

Basically, i am designing the vue component where i am giving URL input and download the innerHTML of page content and save it as a HTML. Any help on this part??

Comments

Comment posted by Estus Flask

It’s unclear what’s the problem. As for the current page, you can do this as you did. As for any other page, you can’t do this on client side at all. It could be rendered in iframe to get HTML, but any reputable website puts a restriction on that.

Comment posted by learningMonk

I am updating the codesandbox demo.

Comment posted by Estus Flask

As I said, you can’t do this efficiently on client side, not to mention that you likely expect HTML to have JS applied, while it’s static when it’s fetched. You need to fetch and probably render pages on server side.

Comment posted by learningMonk

For current page, for same domain intranet site url i am going to use. To avoid CORS issue or etc. But my sample code i missed something so it is not working

Comment posted by Estus Flask

If it’s guaranteed that there’s no CORS then it’s ok, the question doesn’t say this. You need to append

Comment posted by learningMonk

I have added codesandbox link … Can you check once?

By