Create HTML canvas in Client Script - discrepancies between Corp instance and Personal Dev

chadlockwood
Kilo Sage

I have built a portal page to generate a visitor badge label, in Service Portal. In the Advanced View, I want to use a UI Action or Client Script, on the table record, to generate a badge label from the record data.

In my personal Dev instance, I created an onChange client script using this code:

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
	if (isLoading || newValue === '') {
		return;
	}

	//Type appropriate comment here, and begin script below
	// Create a canvas element
	var canvas = document.createElement('canvas');
	canvas.width = 500;
	canvas.height = 400;

	// Get the drawing context
	var ctx = canvas.getContext('2d');

	// Then you can do stuff, e.g.:
	ctx.fillStyle = '#f00';
	ctx.fillRect(20,10,80,50);
	var new_image_url = canvas.toDataURL();
	g_form.setValue('u_visitor_badge_encoded', new_image_url);
}

When this code runs, it populates the u_visitor_badge_encoded field with the Base64 data.

In our Corporate dev instance, the same code generates this error:

onChange script error: TypeError: Cannot read property 'createElement' of null function () { [native code] }

I even reduced the code in both instances to:

console.log(document);

In my dev, it prints the document object to the console. In our corp dev, it prints null.

Is there some configuration that we may have setup in our corp instance that is not allowing access to document from the client script? Could it possibly be some kind of ACL? 

I am actively using Chrome and Opera browsers for development. My dev and our corp dev are both on Kingston P5.

1 ACCEPTED SOLUTION

chadlockwood
Kilo Sage

Turns out I had to create a system property glide.script.block.client.globals and set it to false in the scope. 

View solution in original post

4 REPLIES 4

shawna
Tera Guru

I would suggest to create a simple widget for this rather than using DOM manipulation. 

Shawna,

How would a widget help me here? I don't need to see it, I just need to generate the Base64 data. It works in my Dev environment but not in our Corp Dev. 

shawna
Tera Guru

My initial thoughts were that ServiceNow is against accessing DOM from Client script and I would define the canvas in the widget rather than creating it on the fly. 

 

 

For accessing DOM in client script, try this object. so use "this.document.createElement" rather than document.createElement

var doc = this.document ? this.document : document;

 

Reference:

https://snprotips.com/blog/2017/7/21/how-to-enable-dom-manipulation-in-the-servicenow-service-portal

 

 

chadlockwood
Kilo Sage

Turns out I had to create a system property glide.script.block.client.globals and set it to false in the scope.