New cs/styles created runtime

Hi,
I’m using the NGClient and I would like to create some css classes runtime because I need to fill them by reading some colors from the database.

Does exist a way to do that?

Hi Marco,

yes you can.
Just write your CSS, then convert it to Base64 and add it as a stylesheetlink like this:

var myCSS = '.bg-white { background-color: white; }';
var b64 = utils.stringToBase64(myCSS);
/** @type {ngclientutils.tag} */
var _oTag = {
	tagName: "link",
	attrs : [{
		name: "rel",
		value: "stylesheet"
	},{
		name: "href",
		value: "data:text/css;base64," + b64
	}]
}

plugins.ngclientutils.contributedTags.push(_oTag);		
plugins.ngclientutils.replaceHeaderTag('link','rel','stylesheet',null);

Please note: you need the ngclientutils plugin, also utils.stringToBase64() is a function that has been added in 2020.3 release (if I’m not mistaken…)

Hope this helps

Hi Marc,
thank you for your reply.
I did some tries before answering.

Your code works pretty well but Chrome prevents it’s execution (so my CSS classes created at runtime are listed into the page when I inspect it but they are not taken in consideration by chrome because it considers them a security issue).

This is the error:
[attachment=0]custom css error.PNG[/attachment]

Thank you in advance for your time

custom css error.PNG

Hi Marco,

I think you get this warning because you didn’t convert the CSS string into base64.
This should be done using this line of code:

var b64 = utils.stringToBase64(myCSS);

Hope that helps

Hi, Marc and Marco.

In the sample code, object ‘oTag’ is missing the closing curly brace (})…most likely, a cut-and-paste error. :)

Hi Kim, thank you for your reply! I think I closed the oTag when I pasted it into my .js because the compiler was giving error :D

However, I created those two functions:

function addStyleSheet(stylesheetContent) {
	var _stylesheetContentB64 =utils.stringToBase64(stylesheetContent)
	addCSSReference("data:text/css;base64," + _stylesheetContentB64)
}


function addCSSReference(URL){
	
	if(scopes.svySystem.isSmartClient()) //not allowed in smartclient
		return 
		
	    var _oTag = {
			        tagName: "link",
			        attrs : [{
				         name: "rel",
				         value: "stylesheet"
			        },{
			         name: "href",
			         value: URL
			        }]
        }

        plugins.ngclientutils.contributedTags.push(_oTag); 
	
}

You can call “addStyleSheet” function by giving any css within.
I’m still getting this error:
[attachment=0]error.PNG[/attachment]

Thank you
Marco

error.PNG