How to use DOM element within client script in UI Builder

Hari1
Mega Sage

Hi,

I am trying to run the below code within client script in UI Builder.

function handler({
    api,
    event,
    helpers,
    imports
}) {
    helpers.timing.setTimeout(function() {
        var script = this.document.createElement('script');
        script.src='https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js';
        script.onload = function() {
            takeScreenshot();
        };
        this.document.head.appendChild(script);
    });

    function takeScreenshot() {
        html2canvas(this.document.body, {
            onrendered: function(canvas) {
                var canvasVal = canvas.shadowRoot;
                var dataURL = canvas.toDataURL("image/png");
                var link = this.document.createElement("a");
                link.href = dataURL;
                link.download = "screenshot.png";
                link.click();
            }
        });
    }
}

I see an error message stating "html2canvas is not a function" in the browser log. Thanks.

15 REPLIES 15

Sheldon  Swift
ServiceNow Employee
ServiceNow Employee

Hi @Hari1 - html2canvas isn't loaded when you're calling the function. Try waiting 1 second and then enter typeof html2canvas in the browser console. The output should be "function".

Also, please avoid posting the same question multiple times: Issue with Client Script in UI Builder 

Hi @Sheldon  Swift,

I see the script is working fine in the incident form using the UI Action. But when i use the same script using the client script in the UI Builder. I don't see this to be working. I am not able to use document, this, canvas methods in UI Builder.

I have used helpers.timing.setTimeout to make use of this and document but i don't see any values when i log this.document.body, this.document.

UI Builder is not supporting the DOM elements. Can you please help!

Brad Tilton
ServiceNow Employee
ServiceNow Employee

UI Builder doesn't directly support accessing the DOM because of the shadow dom it uses, and even using the unsupported hack with setTimeout may not work. 

What is your overall requirement here? You may be able to accomplish it with a small custom component instead.

Hi @Brad Tilton, Thank you for your response. The requirement is to capture the screenshot of the UI Builder form on click on a button. The button component will be added on the UI Builder form. Once the button is clicked, we need the screenshot of the form to captured and it needs to be attached to the UI Builder form. Please let me know if you need any additional details.