Search code examples
javascripthtmlscreenshot

Take a full scrolling screenshot of a different page using Vanilla JavaScript


How can I take a scrolling screenshot of a webpage with a different domain name using Vanilla JavaScript. The website should ask the user to enter a webpage URL. The website should then display a scrolling screenshot of that webpage.

I have an input tag and a button in my HTML code:

<input type="url" id="input-URL">
<button id="get-screenshot">Get scrolling image</button>

I have a div which should contain the scrolling screenshot of the webpage:

<div id="show-webpage"></div>

When the user enters a URL into the input box and presses the button, a scrolling screenshot should be shown in the div with the id show-webpage.

I have tried using the html2canvas module to do this. However, when I try to access a different webpage using this module, I receive the error:

Access to script at 'file:///file-path' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.

Through research, I have found that this is because of the CORS policy in other websites which stops my website from viewing the webpage.

How can I fix this error and correctly take a scrolling screenshot of the webpage.

I want to be able to take screenshots without needing to upload my website to a web server. The website should be able to run on my local machine.


Solution

  • The CORS policy is a security feature implemented by web browsers that restricts web pages from making requests to a different domain than the one that served the web page. But...

    You could use a proxy service like cors-anywhere (its only recommended for development projects):

    const url = 'https://cors-anywhere.herokuapp.com/' + document.getElementById('input-URL').value;
    fetch(url)
        .then(response => response.text())
        .then(data => {
            document.getElementById('show-webpage').innerHTML = data;
            // Use html2canvas or similar to take a screenshot
        });