Error element is not attached to a document html2canvas

What is the meaning of this error? and how to fix it

I was having the exact same problem — I wanted to call HTML2Canvas on button click. No matter how I wrote the HTML2Canvas call, I would get an «Uncaught (in promise) undefined…Promise rejected (async)» error. Finally, I learned a little bit about how promises work and found the solution was adding a catch:

function myFunction() {
    html2canvas(document.querySelector("#capture")).then(canvas => {          
        	var base64encodedstring = canvas.toDataURL("image/jpeg", 1).replace("data:image/jpeg;base64,", "");
        	j$("[id$='inputHidden']").val(base64encodedstring);
        	console.log('Saving...');
        	mySaveFunction();
        })
    	.catch(function (error) {
        	/* This is fired when the promise executes without the DOM */    
    	});
}

Word of warning, I’m a total javascript novice and understand very little about how promises work. My code worked fine without the .catch() if I used it outside of a function. I’m assuming that somehow, when you encapsulate it, it no longer has the correct DOM access and the promise fails.

#reactjs

#reactjs

Вопрос:

В чем смысл этой ошибки? и как это исправить

Я пытаюсь преобразовать данные html в холст с html2canvas помощью .

мой код:

  html2canvas(ReactHtmlParser(pages[a])).then(function(canvas) {
     console.log(canvas);
 });
 

Ответ №1:

Итак, в основном, что вы хотите сделать, это получить a canvas из вашего react DOM.

Теперь, что вам нужно сделать, это предоставить обычный DOM html2canvas(normalHTMLDomFromJS) .

Но то, что вы делаете, это передать ReactDOM (который является простыми объектами javascript) в html2canvas

Element is not attached to a document html2canvas происходит, когда вы передаете что-то, кроме jsDOM html2canvas(shouldNotBeJSDOMToThrowError) , что означает, что ReactHtmlParser(pages[a]) это не возвращает js DOM (его возвращающий react DOM(что-то вроде {}))

Я полагаю, вы делаете это с помощью приложения react, поэтому вы должны получить a ref из своего элемента, затем вы можете получить доступ к своему обычному js DOM из ref.current

проблема с github

 import React, { useRef } from "react";
import html2canvas from "html2canvas";
import ReactDOM from "react-dom";

function captureScreenshot(rootElem) {
    alert("Now.. Preparing Screenshot");
    console.log(rootElem);

    html2canvas(rootElem).then(canvas => {
        document.body.appendChild(canvas);
    });
}

function App(props) {
    const rootRef = useRef(null);
    const onClick = () => {
        const elements = rootRef.current;
        captureScreenshot(elements);
    };

    return (
        <div ref={rootRef}>
            <h2 style={{ color: "pink" }}>bla bla bla</h2>
            <button onClick={onClick}>ScreenShot</button>
        </div>
    );
}

ReactDOM.render(<App />, document.getElementById("root"));
 

Комментарии:

1. Я не могу использовать для строки HTML? Я не хочу показывать его в том же документе! Я хочу добавить холст в другую функцию для сохранения изображения.

2. Ошибка заключается в том, что вы передаете react DOM(простые объекты) в html2canvas, вы должны использовать ссылку или присвоить идентификатор вашему элементу и сделать это следующим образом html2canvas(document.getElementById(«my-id)), а с помощью вашего canvas вы можете html2canvas(rootElem).затем (canvas => {SaveImage(холст); });

Элемент, который вы пытаетесь отобразить, не находится в DOM документа.

Итак, как исправить эту проблему?

0.5 в порядке, но когда я обновился до 1, я получил эту ошибку

Поделитесь примером на jsfiddle

Я попытался загрузить html2canvas js (версия 1) и мое приложение js после тела HTML, и эта проблема была исправлена ​​для меня.

Есть ли у кого-нибудь исправление этой проблемы, у меня такая же проблема при использовании на странице cshtml ASP.Net MVC.

Если вы используете jQuery для поиска DIV, используйте
html2canvas ($ («# element») [0]). then (function (canvas) {
$ («# элемент-выход»). append (холст);
});

Но я не могу сделать изображение карты Google с помощью html2canvas (все изображения карты не появляются). Может ли кто-нибудь помочь мне, как сделать то же самое в cshtml ???

@cjcortez @RaghavPrabhu исправляет ли вышеприведенное решение smartbepl для вас, предполагая, что вы используете jQuery или другую библиотеку, которая предоставляет список элементов вместо одного Element ?

У меня это работает!
html2canvas ($ (‘# div’). get (0)). then (function (canvas) {
console.log (холст);
});

@jeremielodi Спасибо, это

Я пробовал код, аналогичный приведенному выше, но, возможно, ошибка, которую я получаю, не совсем связана: Uncaught (in prom) undefined … Promise rejected (async)

У меня была точно такая же проблема — я хотел вызвать HTML2Canvas при нажатии кнопки. Независимо от того, как я писал вызов HTML2Canvas, я получал ошибку «Uncaught (in prom) undefined … Promise rejected (async)». Наконец, я немного узнал о том, как работают обещания, и обнаружил, что решение добавляет уловку:

function myFunction() {
    html2canvas(document.querySelector("#capture")).then(canvas => {          
            var base64encodedstring = canvas.toDataURL("image/jpeg", 1).replace("data:image/jpeg;base64,", "");
            j$("[id$='inputHidden']").val(base64encodedstring);
            console.log('Saving...');
            mySaveFunction();
        })
        .catch(function (error) {
            /* This is fired when the promise executes without the DOM */    
        });
}

Предупреждение: я новичок в javascript и очень мало понимаю, как работают обещания. Мой код отлично работал без .catch (), если я использовал его вне функции. Я предполагаю, что каким-то образом, когда вы инкапсулируете его, у него больше нет правильного доступа к DOM, и обещание не выполняется.

@niklasvh с последней версией html2canvas. Я получаю ошибку Uncaught (в обещании): undefined. Не могли бы вы мне помочь.

image

image

Для меня это отлично работает:

function downloadURI(uri, name) {
    var link = document.createElement("a");

    link.download = name;
    link.href = uri;
    document.body.appendChild(link);
    link.click();
    clearDynamicLink(link); 
}

function DownloadAsImage() {
    var element = $("#table-card")[0];
    html2canvas(element).then(function (canvas) {
        var myImage = canvas.toDataURL();
        downloadURI(myImage, "cartao-virtual.png");
    });
}

в хроме работает нормально, но в IE11 не работает … T_T;

Непойманный (в обещании): неопределенная ошибка

@bandacs вы нашли решение этого? Я получаю точную ошибку на вашем снимке экрана.

Я использую версию 1.0 alpha 12, и у меня такая же проблема. Я пробовал все эти решения.

Я пробовал это решение от @smartbepl
html2canvas ($ («# element») [0]). then (function (canvas) {
$ («# элемент-выход»). append (холст);
});

Я пробовал это от @jeremielodi
html2canvas ($ (‘# div’). get (0)). then (function (canvas) {
console.log (холст);
});

Я также попробовал решение leandrocgsi и попытался добавить уловку, как предлагает @ikemike .

Чтобы упростить его и обеспечить загрузку всех элементов в DOM, я помещаю функцию take_screenshot ().

функция take_screenshot ()
{
html2canvas ($ («. image__container») [0]). then (canvas => {
console.log («пожалуйста, работайте, я схожу с ума»);
});
}
Затем я вызываю take_screenshot () прямо из консоли javascript, чтобы убедиться, что все загружено.
Я получаю ту же ошибку Uncaught (в обещании) undefined.

почему я потерпел неудачу в чирио?

   .get(url)
   .end((err, res) => {
       cheerio.load(res.text)
       html2Canvas($('#statuses').get(0), {
           allowTaint: true
       }).then(function(canvas) {})
})
Uncaught (in promise) Error: Element is not attached to a Document

Теперь есть еще одно соглашение о вызовах.
Версия 0.5 ожидала узел в массиве, а теперь вы даете его напрямую.
В версии 0.5 была опция «onrendered», а теперь вы используете конструкцию «then».

herbertxy

Bug reports:
Failed to execute ‘createPattern’ on ‘CanvasRenderingContext2D’: The image argument is a canvas element with a width or height of 0.

image

I console the value of width and height , find that the height is less than 1 caught this error
image
image

Specifications:

  • html2canvas version tested with: 1.4.1
  • Browser & version: chrome latest
  • Operating system: windows 10

solution:
calculateBackgroundRendering function return value width height may be less than 1
and createPattern function throw error

bjornol

Cant render custom fonts in svg. Fonts are working on the website but wont render proper.
Outside the svg image the fonts are correct but not inside the svg image.

Are using the latest version and the issue remains the same on all latest browsers.

This how it looks like on the site:**

website

This is how it is rendered

The fonts outside the svg is the right font but the svg is not.
rendered

Code

code.txt
code

Svendolin

Hello world..and other people!

Got the Problem of «Uncaught (in promise) Error: Element is not attached to a Document!
My console always gives me that error. In tutorials or videos from others it ALWAYS works…But not here on my side :(

Here is the code where I wanted to kinda download the image as a PNG file with html2canvas:

https://github.com/Svendolin/All-about-Javascript (TASK 11_HTML2CANVAS -> downloader.html)

I have no idea what’s wrong. :(

Thank you for your support, dear reader of this text!

0xCTF

In this website https://www4.inscription.tn/ORegMx/servlet/AuthentificationEtud?ident=cin
i’m trying to get an omage data url of the captcha, the current shown one
so i wrap <img to a div

<div id="divPage">
<img src="https://www1.inscription.tn/ORegMx/capito.png"/></div>

don’t know why it’s not working without div, anyway
this test code in jsfiddle working fine

http://jsfiddle.net/hmj1cby4/1/

but in chrome console and firefox console using this code

$.getScript("https://html2canvas.hertzen.com/dist/html2canvas.js", function() {
        html2canvas($("#divPage"), {
            onrendered: function(canvas) {
                document.body.appendChild(canvas);
               },
                       allowTaint: true,
                    taintTest: false
         });
  
});

i got these errors
firefox: Error: Element is not attached to a Document
chrome: Uncaught (in promise) Error: Element is not attached to a Document

What the issue here?
i will inject this code to an anroid webview to get an image data url of the captcha and put it in imageView

Hope someone help, i’m out of ideas, i spent many hours trying to take that screenshot of the captcha without success

tarekeldeeb

  • You are using the latest [version]
  • You are testing using the non-minified version of html2canvas and checked any potential issues reported in the console

Bug reports:

Arabic text is rendered bad. All letters are not joint and misplaced.
The bug —>
somefilename
The correct —>
somefilename-correct

Specifications:

  • html2canvas version tested with: 1.0.0-alpha.10
  • Browser & version: Chrome Version 63.0.3239.132 (Official Build) (64-bit)
  • Operating system: Windows 10 64-bit

msherif4u

I have used figure property to set the background image and one image using IMG tag inside that figure tag. I am using html2canvas function to download it. I have an issue with opacity. It works fine if I set the opacity for the main card and download it. But if I set the opacity for another image which is in IMG tag, in the browser it shows perfect, but when downloaded it gives 100% opacity. Please check the attached images.
in browser
0l0a7

downloaded image
JsQYA

lili21

Please make sure you are testing with the latest release of html2canvas.
Old versions are not supported and issues reported for them will be closed.

Please follow the general troubleshooting steps first:

  • You are using the latest version
  • You are testing using the non-minified version of html2canvas and checked any potential issues reported in the console

Bug reports:

the promise return from html2canvas function never resolve, if there is a img element with loading attribute as «lazy»

the reproduce demo
jsfiddle

Specifications:

  • html2canvas version tested with: 1.4.1
  • Browser & version: Safari 15.5
  • Operating system: macOS Big Sur Version 11.6.7

chheng05

ghrst6688

malakarbiplab

julianazadarko

Please follow the general troubleshooting steps first:

  • You are using the latest version
  • You are testing using the non-minified version of html2canvas and checked any potential issues reported in the console

Bug reports:

If there is text with an underline, the line is rendered too close to the text in the screenshot.
This is for the css property text-decoration: underline;

http://jsfiddle.net/bcqoexmt/

Specifications:

  • html2canvas version tested with: 1.4.1
  • Browser & version: Chrome, Version 106.0.5249.103
  • Operating system: Windows 11

kikifang

Description

I’m trying to draw a SVG image (please see code.html.txt) on the html canvas, using html2canvas v1.0.0-alpha.12. But, not successful.

The html2canvas might not support all kinds of SVG elements in Chrome browser, I guess. I’m not sure that this is a Chrome security restriction, or a html2canvas fault. This has blocked my work.

Oops… :(

Specifications:

  1. html2canvas version tested with: 1.0.0-alpha.12
  2. Mac
  • Browser & version: Chrome Version 66.0.3359.181
  • Operating system: Mac OS Version 10.13.4.
  1. Windows
  • Browser & version: Chrome Version 62.0.3202.94
  • Operating system: Windows latest version

ThalyssonLeite

I does not support the inline style: box-shadow: inset …

Ex: box-shadow: inset 0px 0px 11px 4px black

zhoujun494

Hi,
I was faced that textarea cannot break line with capturing
hopes give some help
thanks!

Specifications:

  • html2canvas version tested with:1.0.0-rc.3
  • Browser & version:latest version
  • Operating system:win 10

naseem1amjad

Bug reports:

External / Referenced SVG using IMG tag is not rendering properly on Chrome and Not Showing in FireFox when Taking ScreenShot using HTML2Canvas Hosted WebPage.

Specifications:

  • html2canvas version tested with: 1.4.1
  • Browser & version: Chrome Version 99.0.4844.51 (Official Build) (64-bit)
  • Operating system: Windows10

HTML Code:

<div id="capture" style="padding: 10px; background: #f5da55">
<h4 style="color: #000; ">Hello world!</h4>
External Svg=><img src="heart_full.svg" width="50px" height="50px" style="height: 50px; width: 50px;">
Jpg=><img src="PICA6.jpg"><BR>
<p>Again Inline SVG</p>
<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="50" height="50" style="height: 50px; width: 50px;">       
      <circle id="1" cx="25" cy="25" r="20" fill="#A52A2A"></circle>
</svg>
</div>

JavaScript Code:

function screenshot(){
html2canvas(document.querySelector("#capture")).then(canvas => {
document.body.appendChild(canvas)
});
}

ScreenShots:

Rendering on Chrome
Screenshot of rendered page on Chrome

Rendering on FireFox
Screenshot of rendered page on FireFox

shub197

6609ms Error loading image https://myurl

my pdf generating successfully but without image ,i want image in my pdf

iamdman

  • You are using the latest version
  • You are testing using the non-minified version of html2canvas and checked any potential issues reported in the console

I am getting a CSP violation when using html2canvas within my chrome extension. The following replaceChildren line is the culprit. This is not a bug I understand but and issue with my CSP directive I suppose. Any help on how to get around or suppress this error in the best way possible without opening up security holes would be appreciated.

Full error from Chrome dev tools:

Refused to run the JavaScript URL because it violates the following Content Security Policy directive: «script-src ‘self’ ‘wasm-unsafe-eval'». Either the ‘unsafe-inline’ keyword, a hash (‘sha256-…’), or a nonce (‘nonce-…’) is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the ‘unsafe-hashes’ keyword is present.

{
  "name": "ImageCatcher",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": [
    "downloads",
    "webNavigation",
    "tabs",
    "declarativeContent",
    "activeTab",
    "storage",
    "scripting",
    "webRequest",
    "contextMenus"
  ],
  "externally_connectable": {
      "ids": ["*"]
  },
  "content_security_policy":{
  	"extension_page": "default-src 'self'; style-src 'self' 'unsafe-inline' chrome-extension:; img-src 'self' blob: data:; img-src 'data'; frame-src chrome-extension:; script-src 'self'"
  },  
     "content_scripts": [{
          "js": ["jquery.min.js", "html2canvas.min.v1.4.1.js", "content.js"] 
    }], 
    "background": {
        "service_worker": "background.js"
  }

}

Specifications:

  • html2canvas version tested with: latest build v1.4.1 (both min and full versions give same error)
  • Browser & version: Version 104.0.5112.102 (Official Build) (64-bit) CHROME
  • Operating system: Windows 10 Professional 64BIT

maynarddemmon

At line 2031: var processColorStops = function (stops, lineLength) {

If the lineLength is 0 it throws an error: html2canvas.min.js?_cb=1664835040654:7200 Uncaught (in promise) TypeError: Failed to execute ‘addColorStop’ on ‘CanvasGradient’: The provided double value is non-finite.

It sets the stop to NaN which makes sense since it does a divide by zero towards then end of that function. It probably just needs a fail fast for zero length since it doesn’t need to render the gradient in this edge case.

On latest chrome (106), OSX and html2canvas version 1.4.1

Design2k

Please make sure you are testing with the latest release of html2canvas.
Old versions are not supported and issues reported for them will be closed.

Please follow the general troubleshooting steps first:

  • You are using the latest version
  • You are testing using the non-minified version of html2canvas and checked any potential issues reported in the console

Bug reports:

Cool product.

We’ve been prototyping an web app using CSS filters. Basically the user can upload a photo, apply the effect and download. The app is built using reactJS.

The issues we are running into is exporting the image with the filter. The image exports, no filter is rendered. html2canvas states it does not work on css filters. Any workaround for this?

Do you have a work around for this?

Specifications:

  • html2canvas version tested with:
  • Browser & version:
  • Operating system:

EmmanuelPonnudurai

Hello. I have noticed this point in the readme,

The script is still in a very experimental state, so I don’t recommend using it in a production environment nor start building applications with it yet, as there will be still major changes made.

Why this recommendation? Are there any security/known issues?

We are trying to use this library in our application and for what we need, its working fine. But we noticed this point and wanted to make sure we aren’t missing an important detail.

I know its mentioned experimental, but trying to get more details on the specific reason why it’s still experimental and not production ready.

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

Provided element is not within a Document

While working on the web-page and creating featured elements. We might have come requirement of sharing widget on social media like the attached image or create a screenshot of current screen for proctoring purpose.

In both scenario we need to create image on run time as data coming on page is dynamic. To take snapshot or screen capture we use html2canvas JS plugin.

While using html2canvas plugin most of user mostly who is upgrading their core from older version to newer face issue of “Uncaught (in promise) Provided element is not within a Document” 

Why it’s coming?

There are mainly 3 reasons why this issue can arise.

  1. Class or ID you are using not exist in current page DOM
  2. You are upgrading your html2canvas core.

Solution

To solve issue 1 just verify your CLASS or ID name in DOM or correct your name

If you are using latest version of html2canvas script just ensure don’t not use jQuery object in code.

Recommended Articles

Like instead of using

$(“.capture”) use document.querySelector(“#capture”) 
Seems like html2canvas has remove the support of jQuery in their latest core and added support for jqlite commands, to use jqlite you don’t require any external plugin.

Most browser have inbuilt support for jqlite commands. for more jqlite commands.

Post Views: 941

Element is not attached to the page document, but I’m sure it is?

I posted this on StackOverflow today and I didn’t get any answers. So here goes:

EDIT5 : Here’s the file : https://drive.google.com/file/d/1wlEtvYntnJRDA-OZ3IQPaLmECL6YyHl4/view?usp=sharing You can compile and check for yourself.

I’m using Python + Selenium with VSCode and Vscode throws me this error whenever my code restarts.

I’ve got code set in a loop to grab an element by class and then do operations on that element, specifically this :

self.actions.context_click(self.driver.execute_script("elm = document.getElementsByClassName('member-3-YXUe')[arguments[0]]; return elm", cnt)).perform() 

This code is set in a loop, but it only works properly the first time. The second time it always throws the above error. I couldn’t for the life of me figure out why it does that. Put in mind that the value of «elm» as is obvious is refreshed in each iteration, and I’m pretty sure the element I’m targeting is still there and has the same properties I’m referencing it by. I even tried to make a long sleep delay in order to make sure quick loading between page refreshs is not a problem. Nothing worked.

It always works the first time, and it always fails the second time with the same error. What could be causing this?

EDIT: I also tried using Python to get the element and I also tried separating the element-finding from the perform()

EDIT2 : I’m working with Discord. A Discord server’s user element from the server user list to be specific.

EDIT3: Here’s my loop code. Perhaps it’s a misreferenced error or something.

while (users <= 5):      users += 1     #cnt += 1      sleep(2)      #scroll down user list     print("n------------------------------Scroll down list------------------------------")          #elm.click()     self.driver.execute_script("         elm = document.getElementsByClassName('membersWrap-2h-GB4')[0];         elm.scrollTo(0, elm.scrollHeight + 1000);         //elm.innerHTML = '';         ")      print("n------------------------------get user user------------------------------")     sleep(1)      #get user      user = self.driver.execute_script("elm = document.getElementsByClassName('member-3-YXUe')[arguments[0]]; return elm", cnt)      print("n------------------------------click on a user------------------------------")     sleep(2)      #right click user and message     print("n0--------------------")      self.actions.context_click(self.driver.execute_script("elm = document.getElementsByClassName('member-3-YXUe')[arguments[0]]; return elm", cnt)).perform()      print("n1--------------------")     elm = self.driver.find_element_by_xpath("//div[contains(@id, 'user-context-message-user')]")      print("n2--------------------")     elm.click()      print("n------------------------------Add Friend------------------------------")     #sleep(2)     #elm = self.driver.find_element_by_xpath('//button[contains(@class, "button-38aScr")]')     #elm.click()          print("n------------------------------type message------------------------------")     sleep(2)      elm = self.driver.find_element_by_xpath('//div[contains(@data-slate-object, "block")]')     elm.send_keys("Hoi")     elm.send_keys(Keys.RETURN)      sleep(2)     print("n------------------------------Go back to server------------------------------")     elm = self.driver.find_element_by_xpath('//div[contains(@data-list-item-id, "guildsnav___756234166877683762")]')      elm.click()     cnt += 1 self.driver.get("https://discord.com/channels/756234166877683762/756235051540414584")     sleep(5)  self.driver.quit() 

EDIT4 : More clarification — The first time the code is run I’m able to log in into discord, go to the specific server, get the first user in the server, DM them, and then go back to the server. At this point the bot gives the error, when I try t grab the same user or the next user in the indexed list. I’ve also tried grabbing users by attributes rather than classes. I’m not sure this is a Discord protection thingie, it really smells of a bad loop or Python/VSCode error.

EDIT6: I tried looping the entire script, closing and re-opening the webdriver and the chrome window. Somehow this doesn’t turn up with the error, while trying twice in the same window would lead to the second try failing as mentioned before. Still don’t know why this happens. Maybe it has something to do with persistent values of variables or the local browser storage? For when the session is terminated and restarted after every iteration nothing wrong happens.

Понравилась статья? Поделить с друзьями:
  • Error element div not allowed as child of element span in this context
  • Error either local is duplicate or eth0 is a garbage
  • Error eisdir illegal operation on a directory read
  • Error einval at least one inheritable acl entry is required
  • Error ehooks core library is not found