Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

jquery - How to render HTML pages as PNG/JPEG images on single click using URLs Tabs array in Javascript only?

I am building a chrome extension using Javascript which gets URLs of the opened tabs and saves the html file, but the problem with html is that it does not render images on webpages fully. So i changed my code to loop each URLs of the tabs and then save each html pages as image file automatically in one click on the download icon of the chrome extension. I have been researching for more than 2 days but nothing happened. Please see my code files and guide me. I know there is library in nodejs but i want to perform html to jpeg/png maker using chrome extension only.

Only icons i have not attached which i have used in this extension, all code i have and the text in popup.js which is commented i have tried.

Current output of the attached code enter image description here

Updated popup.js

File popup.js - This file has functions which gets all the URLs of the opened tabs in the browser window

// script for popup.html
window.onload = () => {  
    
    // var html2obj = html2canvas(document.body);
    // var queue  = html2obj.parse();
    // var canvas = html2obj.render(queue);
    // var img = canvas.toDataURL("image/png");
    
    let btn = document.querySelector("#btnDL");
    btn.innerHTML = "Download";

    function display(){
        // alert('Click button is pressed')
        window.open("image/url");
    }

    btn.addEventListener('click', display);
}

chrome.windows.getAll({populate:true}, getAllOpenWindows);

function getAllOpenWindows(winData) {

    var tabs = [];
    for (var i in winData) {
      if (winData[i].focused === true) {
          var winTabs = winData[i].tabs;
          var totTabs = winTabs.length;
  
          console.log("Number of opened tabs: "+ totTabs);
  
          for (var j=0; j<totTabs;j++) {

                tabs.push(winTabs[j].url);
                
                // Get the HTML string in the tab_html_string
                tab_html_string = get_html_string(winTabs[j].url)
                
                // get the HTML document of each tab
                tab_document = get_html_document(tab_html_string)

                console.log(tab_document)

                let canvasref = document.querySelector("#capture");
                canvasref.appendChild(tab_document.body);

                html2canvas(document.querySelector("#capture")).then(canvasref => {
                    
                    document.body.appendChild(canvasref)
                    var img = canvasref.toDataURL("image/png");
                    window.open(img)

                });

          }
      }
    }
    console.log(tabs);
}

function get_html_document(tab_html_string){
    
    /**
     * Convert a template string into HTML DOM nodes
     */
    
    var parser = new DOMParser();
    var doc = parser.parseFromString(tab_html_string, 'text/html');
    return doc;

}

function get_html_string(URL_string){

    /**
     * Convert a URL into HTML string
     */
    
    let xhr = new XMLHttpRequest();
    xhr.open('GET', URL_string, false);

    try {
        xhr.send();
        if (xhr.status != 200) {
            alert(`Error ${xhr.status}: ${xhr.statusText}`);
        } else {
                return xhr.response                                
            }

    } catch(err) {
        // instead of onerror
        alert("Request failed");
    }
}

File popup.html - This file represent icon and click functionality on the chrome browser search bar

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
    <script src= './html2canvas.min.js'></script>
    <script src= './jquery.min.js'></script>
    <script src='./popup.js'></script>

    <title>Capture extension</title>
    
        <!--
          - JavaScript and HTML must be in separate files: see our Content Security
          - Policy documentation[1] for details and explanation.
          -
          - [1]: http://developer.chrome.com/extensions/contentSecurityPolicy.html
         -->
</head>
<body>

    <button id="btnDL"></button>
    
</body>
</html>

File manifest.json - This file is used by the chrome browser to execute the chrome extension

{ 
      "manifest_version": 2,
      "name": "CIP screen capture",
      "description": "One-click download for files from open tabs",
      "version": "1.4.0.2",
      "browser_action": {
        "default_popup": "popup.html"
      },
      "permissions": [
        "downloads", "tabs", "<all_urls>"
      ],
      "options_page": "options.html"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the library html2canvas which renders any html element, particularly the body element, and from the resulted canvas you can have your image

<script type="text/javascript" src="https://github.com/niklasvh/html2canvas/releases/download/v1.0.0-rc.7/html2canvas.min.js"></script>
<script>
  html2canvas(document.body).then(
    (canvas) => {
      var img = canvas.toDataURL("image/png"); 
    }
  );
</script>

You can get html2canvas from any public CDN, like this one. You don't need nodeJS. Or perhaps directly from the original git repo

<script type="text/javascript" src="https://github.com/niklasvh/html2canvas/releases/download/v1.0.0-rc.7/html2canvas.min.js"></script>

You can also save canvas as a blob

html2canvas(document.body).then(function(canvas) {
    // Export canvas as a blob 
    canvas.toBlob(function(blob) {
        // Generate file download
        window.saveAs(blob, "yourwebsite_screenshot.png");
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...