Search code examples
javascriptcssdomhtml-entitiescss-content

HTML entities in CSS content (convert entities to escape-string at runtime)


I know that html-entities like   or ö or ð can not be used inside a css like this:

div.test:before {
    content:"text with html-entities like ` ` or `ö` or `ð`";
} 

There is a good question with good answers dealing with this problem: Adding HTML entities using CSS content

But I am reading the strings that are put into the css-content from a server via AJAX. The JavaScript running at the users client receives text with embedded html-entities and creates style-content from it instead of putting it as a text-element into an html-element's content. This method helps against thieves who try to steal my content via copy&paste. Text that is not part of the html-document (but part of css-content) is really hard to copy. This method works fine. There is only this nasty problem with that html-entities.

So I need to convert html-entities into unicode escape-sequences at runtime. I can do this either on the server with a perl-script or on the client with JavaScript, But I don't want to write a subroutine that contains a complete list of all existing named entities. There are more than 2200 named entities in html5, as listed here: http://www.w3.org/TR/2011/WD-html5-20110113/named-character-references.html And I don't want to change my subroutine every time this list gets changed. (Numeric entities are no problem.)

Is there any trick to perfom this conversion with javascript? Maybe by adding, reading and removing content to the DOM? (I am using jQuery)


Solution

  • I've found a solution:

    var text = 'Text that contains html-entities';
    var myDiv = document.createElement('div');
    $(myDiv).html(text);
    text = $(myDiv).text();
    $('#id_of_a_style-element').html('#id_of_the_protected_div:before{content:"' + text + '"}');
    

    Writing the Question was half way to get this answer. I hope this answer helps others too.