如何下载网页客户端预览?



我想获取用户提供的URL的图像。

我想发出fetch或 AJAX 请求来获取 HTML 代码,然后用HTML2CANVAS进行转换,但它似乎不起作用。

这是我直接在 Trello 网站的控制台中逐行测试的内容:

function preview_ws(url) {
$.ajax({
url: 'https://cors-anywhere.herokuapp.com/' + url,
success: function(result) {
html = document.createElement("html");
html.innerHTML = result;
}
});
}
preview_ws("https://vuejs.org/v2/guide/components.html#Passing-Data-to-Child-Components-with-Props")
// many errors like GET https://trello.com/images/components.png 404
// the HTML seems to correspond (title is Vue.JS)
html2canvas(html).then(canvas => {
document.body.appendChild(canvas)
});
// then, I have errors:

然后我有错误:

Error while parsing the 'sandbox' attribute: 'allow-storage-access-by-user-activation' is an invalid sandbox flag.
Promise {<rejected>: "Unable to find element in cloned iframe"}
Uncaught (in promise) Unable to find element in cloned iframe

我还尝试过:

html2canvas(html.querySelector("body")).then(canvas => {
document.body.appendChild(canvas)
});
但我得到同样的错误。

那么我怎样才能做出我想要的东西呢?我提醒你,我想要客户端的东西。

请考虑以下代码。

.HTML

<div>
URL <input id="url" type="text" value="https://vuejs.org/v2/guide/components.html#Passing-Data-to-Child-Components-with-Props" /> <button id="go">Fetch</button>
</div>
<div id="preview"></div>

JavaScript

$(function() {
function preview_ws(u) {
console.log("Fetch", u);
$.ajax({
url: 'https://cors-anywhere.herokuapp.com/' + u,
success: function(result) {
var $ht = $("<html>");
$ht.html(result);
console.log("HTML", $ht[0]);
html2canvas($ht[0].body).then(canvas => {
$("#preview").html(canvas);
});
}
});
}
$("#go").click(function() {
var url = $("#url").val();
if (url !== "") {
preview_ws(url);
}
});
});

在这里,我们创建一个 HTML 对象,然后用results填充它。然后,我们可以按照文档中的说明将其传递给 html2canvas。

最新更新