1

i want to add a button to download my html source code of a web page, i was able to do it but the problem is when i add a localhost url it works but when i add live url it open's the url instead of downloading it. so far i tried this

 <a download  href="http://localhost/test-new/">Download Source Code</a>

i also tried this

<button onclick="clicker()">Click me</button>



<script type="text/javascript">

function clicker() {
    var anchorTag = document.createElement('a');
    anchorTag.href = "http://localhost/test-new/";
    anchorTag.download = "download";
    anchorTag.click();


    var element = document.getElementById('divContainer');
    element.appendChild(anchorTag);
}

</script>

both of this working in localhost but not for live url. please help me

Abhishek Kalotra
  • 139
  • 1
  • 3
  • 12

2 Answers2

1

You can use

document.querySelectorAll('*')

to get the source code of a web page

console.log(document.querySelectorAll('*'))
ellipsis
  • 12,049
  • 2
  • 17
  • 33
1

This code should work.

BUT there is one main restriction, that can prevent you from downloading other pages - CORS policy. You can not fetch data from another domain if this policy does not allow it. Modern browsers restricts this for security reasons.

But if you download the current page, no problems will rise. Just see at Dev-Tools Console output for the error:

Access to fetch at 'URL_HERE' from origin has been blocked by CORS...

const btn = document.querySelector('.download-btn');
btn.addEventListener('click', (e) => clicker(e.currentTarget.dataset.url), false);

function clicker(url) {
  fetch(url)
    .then(res => res.text())
    .then(html => downloadAsFile('My file name.txt', html));
}

function downloadAsFile(name, text) {
  const link = createDownloadableLink(name, text);
  const clickEvent = new MouseEvent('click');
  link.dispatchEvent(clickEvent);
}

function createDownloadableLink(fileName, content) {
  let link = document.createElement("a");
  link.download = fileName;
  link.href = `data:application/octet-stream,${content}`;
  return link;
}
<button 
  class="download-btn" 
  data-url="http://localhost:1234/"
>Click me if CORS allow</button>
Evgeny Melnikov
  • 952
  • 7
  • 13