如何仅在 Javascript 中使用 URLs Tabs 数组在单击时将 HTML 页面呈现为 PNG/JPEG 图像? [英] How to render HTML pages as PNG/JPEG images on single click using URLs Tabs array in Javascript only?

查看:18
本文介绍了如何仅在 Javascript 中使用 URLs Tabs 数组在单击时将 HTML 页面呈现为 PNG/JPEG 图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Javascript 构建一个 chrome 扩展,它获取打开的选项卡的 URL 并保存 html 文件,但 html 的问题是它不能完全在网页上呈现图像.因此,我更改了代码以循环选项卡的每个 URL,然后单击 chrome 扩展程序的下载图标,将每个 html 页面自动保存为图像文件.我已经研究了 2 天多,但什么也没发生.请查看我的代码文件并指导我.我知道 nodejs 中有库,但我想仅使用 chrome 扩展将 html 执行到 jpeg/png 制造商.

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.

只有我没有附加的图标,我在这个扩展中使用过,我拥有的所有代码和 popup.js 中的文本是我尝试过的评论.

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.

附加代码的当前输出

更新了 popup.js

File popup.js - 该文件具有获取浏览器窗口中打开的标签的所有 URL 的函数

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");
    }
}

文件 popup.html - 此文件表示 chrome 浏览器搜索栏上的图标和点击功能

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 - 这个文件被 chrome 浏览器用来执行 chrome 扩展

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"
}

推荐答案

您可以使用库html2canvas 呈现任何 html 元素,尤其是 body 元素,并且从结果画布中您可以拥有您的图像

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>

您可以从任何公共 CDN 获取 html2canvas,例如这个.你不需要 nodeJS.或者直接来自原始的 git repo

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>

您也可以将画布另存为 blob

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");
    });
});

这篇关于如何仅在 Javascript 中使用 URLs Tabs 数组在单击时将 HTML 页面呈现为 PNG/JPEG 图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆