In the daily use of Anqi CMS, we often need to display the content of background management, such as article titles, user comments, or other dynamic data, on the front-end page.This content is not just plain text, it also needs to be used in JavaScript code, such as variable values, function parameters, or dynamically generated HTML fragments.However, embedding template variables directly into JavaScript code, if not handled properly, may introduce a significant security vulnerability - cross-site scripting (XSS).

AnQi CMS as a corporate-level content management system that emphasizes security and efficiency, is built with a powerful template engine and provides a series of filters to help us safely process data. Among them,escapejsThe filter is specifically designed to solve XSS problems in JavaScript.

Why is it necessary to embed JavaScript code securely?

Imagine if your website had a comment section where users could submit comments. If a malicious user submitted a comment containing JavaScript code, for example<script>alert('您的Cookie被盗!')</script>And you directly embed this comment content into the JavaScript variable:

<script>
    var comment = "{{ user_comment }}"; // 假设 user_comment 是恶意评论
    // ... 后续代码使用 comment 变量
</script>

When the page loads, this malicious JavaScript code will be executed by the browser, resulting in an XSS attack.An attacker may steal the user's session information (Cookie), modify page content, or even redirect the user to a phishing website.

AnQi CMS understands the importance of data security, and therefore provides in the template design:escapejsSuch tools help us avoid such problems.

escapejsThe principle of the filter.

escapejsA filter is like a 'purifier' that can convert special characters in a string, such as single quotes, double quotes, backslashes, newline characters, etc., to JavaScript-safe\uxxxxEncoding form. Through this transformation, characters that might have been interpreted as part of the JavaScript code structure become ordinary string content, thereby losing the ability to execute malicious code.

To be specific,escapejsIt will convert all characters except letters (a-zA-Z), numbers, spaces, and slashes (/) into\uxxxxA Unicode escape sequence. This way, no matter what the original string contains, it will ultimately become a pure string literal that will not be misinterpreted as JavaScript code by the browser.

How to use it in Anqi CMS templateescapejs?

Using in Anqi CMS, a Django-like template engine,escapejsThe filter is very intuitive. You just need to embed the template variables you need in JavaScript, through the pipe character|withescapejsand connect them.

For example, let's say you have an article title variablearchive.TitleYou want to assign it to a JavaScript variable:

<script>
    // 未使用 escapejs,存在安全隐患
    // var articleTitleUnsafe = "{{ archive.Title }}"; 

    // 使用 escapejs 确保安全
    var articleTitle = "{{ archive.Title|escapejs }}";
    console.log(articleTitle); // 这将安全地打印文章标题
</script>

Ifarchive.Titlehas a value ofIt's an "interesting" articleThen if it is not usedescapejsThe JavaScript code might become:

var articleTitleUnsafe = "It's an "interesting" article"; // 语法错误,甚至可能注入代码

And if it is usedescapejsAfter, it will safely convert to:

var articleTitle = "It\u0027s an \u0022interesting\u0022 article"; // 安全,且是有效的JavaScript字符串

This string, no matter how complex or how many special characters it contains, can be correctly parsed as a normal string in JavaScript, it will not destroy the syntax structure of JavaScript, nor will it execute any potential malicious code.

You can also useescapejsFor more complex scenarios, such as passing dynamic content as parameters to JavaScript functions:

<script>
    function displayContent(title, content) {
        alert("标题:" + title);
        // 这里 content 变量可能包含HTML,后续在DOM中插入时仍需注意上下文
        document.getElementById('article-area').innerHTML = content; 
    }

    // 假设 archive 是当前文档对象
    var safeTitle = "{{ archive.Title|escapejs }}";
    var safeContent = "{{ archive.Content|escapejs }}"; // 注意:这里仅是使其成为安全的JS字符串,而非安全的HTML
    
    displayContent(safeTitle, safeContent);
</script>

<div id="article-area"></div>

In this example,archive.ContentMay contain HTML tags.escapejsWill ensuresafeContentIn JavaScript code it is a safe string literal. But when JavaScript assigns it toinnerHTMLWhen, the browser will interpret it as HTML. Ifarchive.Contentitself contains malicious HTML or JS, it may still trigger XSS in this case.So,escapejsResolved the issue of template variables embedded in JS, but if the content of the JS variable will eventually be inserted into the DOM as HTML, then the JS code itself also needs to ensure that the content is safe, or only inserted into text nodes.

Summary

In the Aiqi CMS, make use ofescapejsThe filter is a critical step to ensure that dynamic data is safely embedded in JavaScript code. It converts potential dangerous characters to safe\uxxxxEncoding effectively prevents cross-site scripting attacks (XSS), thereby ensuring the security of your website's users and data integrity. Always remember to place template variables in<script>When a JavaScript string literal is enclosed in tags, it should be used with `