How to make all external links generated by the `urlize` filter open in a new window?

Calendar 👁️ 69

In the daily content operation of AnQi CMS, we often useurlizeThe filter automatically converts URLs and email addresses in the article content to clickable links for convenience.This undoubtedly provides great convenience for content layout and user experience.However, careful users may notice,urlizeThe filter does not open these links in a new window or tab by default when generating them, which may deviate from our preference to keep external links from affecting the current page browsing.

FacedurlizeThe filter itself does not provide a direct settingtarget="_blank"How can we implement that all external links processed by its parameters can be opened in a new window?The answer is, we can process these automatically generated links with a concise and efficient JavaScript code after the page is loaded.

Dynamically add new window open attribute to external links

The core idea to implement this function is to use JavaScript to traverse all the links on the webpage after the page content is fully loaded, (<a>Label). The program will then determine if each link points to a domain outside the current website. Once an external link is identified, it will be added to the linktarget="_blank"Property, to open in a new window. At the same time, we will also add for enhanced security.rel="noopener noreferrer"Property.

The following is a JavaScript code snippet that implements this function.

document.addEventListener('DOMContentLoaded', function() {
    // 获取当前网站的域名,用于判断链接是否为外部链接
    const currentHostname = window.location.hostname;

    // 遍历页面上所有的链接(<a>标签)
    document.querySelectorAll('a').forEach(link => {
        // 检查链接的href属性是否存在,并且链接的域名与当前网站域名不一致
        // 同时排除锚点链接或内部JS功能链接,这些链接通常没有hostname或与当前hostname相同
        if (link.href && link.hostname && link.hostname !== currentHostname) {
            link.setAttribute('target', '_blank'); // 设置在新窗口打开
            link.setAttribute('rel', 'noopener noreferrer'); // 增强安全性
        }
    });
});

Apply the code to your security CMS website

The recommended approach to make this JavaScript code work on your anqi CMS website and cover all pages is to add it to the website's general template filebase.htmlIn this way, no matter which page the user visits, this script will be executed.

The following are the specific implementation steps:

  1. Enter the Anqi CMS backend and open the template file:First, log in to your AnQi CMS backend. Find 'Template Design' in the left navigation menu, then click 'Website Template Management'.Here you can see the template package you are currently using. Usually, the main template file is namedbase.html(orlayout.html/default.htmlas, the specific filename should be determined according to your template, it usually contains the website's<html>,<head>,<body>basic structure). Click to edit the file.

  2. paste JavaScript code:Copy the provided JavaScript code. Then, inbase.htmlthe file<head>the tag, or more recommended, in</body>Before the tag ends (this ensures that the page content loads first, improving user experience), paste this code. For example, you can place it in</body>Before closing the tag:

        <script>
            document.addEventListener('DOMContentLoaded', function() {
                const currentHostname = window.location.hostname;
                document.querySelectorAll('a').forEach(link => {
                    if (link.href && link.hostname && link.hostname !== currentHostname) {
                        link.setAttribute('target', '_blank');
                        link.setAttribute('rel', 'noopener noreferrer');
                    }
                });
            });
        </script>
        </body>
    </html>
    
  3. Save and clear cache:Save tobase.htmlFile modification. To ensure that the changes take effect immediately, please return to the Anqi CMS backend, click the "Update Cache" feature, and clear the website page cache.

After completing these steps, all will passurlizeFiltering will be automatic, as well as any manually added but not set itemstarget="_blank"All external links will open in a new browser window or tab when clicked.

温馨提示

  • Code placement location:If you place JavaScript inside<head>tags, it is recommended to usedeferAttribute or ensure that the code is withinDOMContentLoadedExecuted in the event listener to avoid manipulating elements when the DOM is not fully loaded. It is more common to place it</body>Before the closing tag.
  • Compatibility:This code uses modern JavaScript syntax and runs well in most modern browsers.If your website needs to support very old browsers, you may need to consider using Babel for transpilation or using more traditional JS selectors and event binding methods.
  • Effect check:After modification, please make sure to click on external links at multiple places on the website front end to verify that the function works as expected.

By using this JavaScript dynamic processing method, we can enjoyurlizeThe convenience brought by the filter, which can also meet the user experience and security needs of opening external links in a new window, making your company CMS website more perfect in content presentation.


Frequently Asked Questions (FAQ)

Q1: WhyurlizeThe filter itself does not providetarget='_blank'options?

A1: urlizeThe filter primarily focuses on identifying URLs in the text and converting them into valid hyperlinks, while automatically addingrel="nofollow"Properties to optimize SEO and avoid link weight loss.target="_blank"It is a decision about user interface and user experience, different websites may have different preferences.To maintain the core responsibility of the filter, and to avoid imposing UI/UX behaviors that may not meet the needs of all users by default, designers usually leave such features to developers to customize through JavaScript or template layers, or to provide unified global settings in the CMS backend (if the CMS has this feature).

Q2: In the coderel='noopener noreferrer'What is it used for? Is it necessary to add?

A2: rel="noopener noreferrer"These two properties are strongly recommended to be added to alltarget="_blank"Enhanced security measures on external links:

  • noopenerPrevent new pages from accessing the original page:window.openerAn object. This means that the new page cannot maliciously control the original page (for example, redirecting the original page to a phishing website).
  • noreferrer: Do not send to the new page.RefererHeader information from the source. This can protect user privacy and prevent the source information from being leaked when users are redirected from your website to other websites. Add them.Very necessaryIt can effectively prevent some phishing attacks and privacy leaks, improving the security of your website.

Q3: How can I make external links in a specific area (such as the article body) open in a new window instead of the entire site?

A3:If you want to target a specific area of the page (for example, only the article content section) for this operation, you can use the selector in the JavaScript codedocument.querySelectorAll('a')Replace with a more specific selector. For example, if the main content of your article is wrapped in a tagid="article-content"of<div>You can change the selector todocument.querySelectorAll('#article-content a'). This is the specific area within which JavaScript will only search and modify the links. The same principle also applies to any container with a specific ID or CSS class.

Related articles

After the Markdown editor is enabled, is the `urlize` filter still effective on the rendered HTML content?

When managing content in Anqi CMS, the introduction of the Markdown editor undoubtedly improves the efficiency and experience of content creation.However, some webmasters familiar with template functions may be curious whether the commonly used `urlize` filter can still work after the Markdown editor is turned on.This indeed is a topic worth discussing. To understand this, we first need to review the handling mechanism of Anqi CMS for Markdown content and the core function of the `urlize` filter.

2025-11-09

The `urlize` filter supports recognizing and converting complex URLs with query strings?

In the daily content operation of AnQi CMS, we often need to deal with various forms of URLs, especially in user comments, article references, or other dynamically generated content, converting plain text URLs into clickable links is a basic and important function.AnQi CMS provides a powerful `urlize` filter to meet this requirement.

2025-11-09

How to use the `{% filter urlize %}` tag block to apply URL conversion at any location in the AnQiCMS template?

In the AnQiCMS template, we often encounter such a scenario: we hope to automatically convert URLs or email addresses appearing in text content into clickable links without manually writing `<a>` tags.This not only improves the user's browsing experience, but also makes our content more interactive.AnQiCMS provides a powerful template engine with the `urlize` filter, which can easily meet this requirement and can be applied flexibly at any position in the template.

2025-11-09

Does the `urlizetrunc` filter automatically add an ellipsis (...) when truncating link text?

In website content operation, we often encounter such situations: long URLs or email addresses appear in the article body, sidebar, or list page.These long links not only affect the appearance of the page, but may also disrupt the layout and reduce the user's reading experience.To solve this problem, AnQi CMS provides powerful and flexible template filters, among which `urlize` and `urlizetrunc` are specifically designed for this purpose.Today, let's delve into the `urlizetrunc` filter, especially how it truncates text after the link

2025-11-09

How does the `urlizetrunc` filter calculate the truncation length when processing URLs containing Chinese or other non-Latin characters?

In the daily content operation of AnQi CMS, we all know that the tidiness and readability of the page content are crucial to the user experience.Especially when an article or list page contains a large number of URLs, how to elegantly display these links while avoiding the destruction of page layout due to long URLs is a common challenge.The Anqi CMS provides a variety of practical template filters, among which the `urlizetrunc` filter is a powerful tool for handling URL display.It not only intelligently converts naked links or email addresses in text into clickable HTML hyperlinks, but also lies in its more powerful functions.

2025-11-09

Can the `urlize` filter be used in combination with other string processing filters in AnQiCMS (such as `replace`)?

In the world of Anqi CMS templates, text processing is an indispensable part of daily content operation.We often need to format and convert the content displayed to users to ensure that the information is clear and the interaction is friendly.Among them, the `urlize` and `replace` filters play an important role.At times, we may wonder if they can work together to bring deeper automation to our content?The answer is affirmative. The `urlize` filter and `replace` filter can be cleverly combined.

2025-11-09

In the `archiveDetail` tag, how to apply the `urlize` filter to enhance the user experience?

In today's website operation, user experience has become a key indicator of whether a website is successful or not.A smooth browsing experience, clear information display, and convenient interaction can significantly enhance user satisfaction.AnQiCMS (AnQiCMS) is a powerful content management system that provides many tools to help operators optimize their websites, among which the clever use of template tags and filters can make twice the effort with half the results.

2025-11-09

Does the `urlize` filter have a significant impact on page loading performance when processing large text and URLs?

When building and operating a website, page loading speed is always a key factor in user experience and search engine optimization.For a content management system (CMS), how to efficiently process and display content without sacrificing performance is its core value.AnQiCMS (AnQiCMS) excels in this aspect with its high-performance architecture based on the Go language.

2025-11-09