In the daily content operation of Anqi CMS, we often useurlizeFilter to conveniently convert URLs and email addresses in article content to clickable links.This undoubtedly provides great convenience for content layout and user experience.urlizeThe filter does not open these links in a new window or tab by default when generating them, which may deviate from the habit we want external links to not affect the current page browsing.
Face tourlizeThe filter itself does not provide direct settingstarget="_blank"How can we implement that all external links processed by the parameter open in a new window?The answer is, we can process these automatically generated links uniformly with a concise and efficient JavaScript code after the page is loaded.
Dynamically add new window open attributes to external links
The core idea of implementing this feature is to use JavaScript to traverse all the links on the web page after the page content is fully loaded, (<a>Label). Next, the program will determine if each link points to a domain outside the current website. Once external links are identified, they will be addedtarget="_blank"Property, opens in a new window. At the same time, we will also add it for enhanced security.rel="noopener noreferrer"properties.
The following is a JavaScript code snippet that implements this feature:
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
To make this JavaScript code work on your secure CMS website and cover all pages, the recommended approach is to add it to the website's common template filebase.htmlEnglish. Thus, no matter which page the user visits, this script will be executed.
The following are the specific implementation steps:
Enter the Anqi CMS backend and open the template file:First, log in to your security CMS backend.Find "Template Design" in the left navigation menu and click "Website Template Management".Here, you can see the template package you are currently using.
base.html(or}layout.html/default.htmland, the specific filename should be determined according to your template, it usually includes the website's<html>,<head>,<body>and basic structure). Click to edit the file.paste the JavaScript code:Copy the provided JavaScript code above. Then, in
base.htmlthe file<head>the tag, or more preferably, in</body>Label the end before (this ensures that the page content loads first, improving user experience), paste this code here. For example, you can place it before</body>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>Save and clean cache:Save to
base.htmlFile modification. To ensure that the changes take effect immediately, please be sure to return to the safety CMS background, click the "Update Cache" feature, and clear the web page cache.
Complete these steps, all passedurlizeThe filter automatically converts, as well as any manually added but not settarget="_blank"The external links, when clicked by the user, will open in a new browser window or tab.
Tips
- Code placement location:If you place JavaScript in
<head>Label inside, it is recommended to usedeferAttribute or ensure that the code isDOMContentLoadedExecuted in the event listener to avoid operating on elements when the DOM is not fully loaded. Place in</body>The closing tag is the more common recommended practice. - 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 JavaScript selectors and event binding methods.
- Effect check:After modification, please make sure to click on external links in multiple places on the website front-end to verify that the function works as expected.
By this dynamic handling method of JavaScript, we can enjoyurlizeThe convenience brought by the filter, while also meeting the user experience and security needs of users who want external links to open in new windows, making your CMS website more perfect in content presentation.
Common Questions (FAQ)
Q1: WhyurlizeThe filter itself does not providetarget='_blank'options?
A1: urlizeThe filter mainly 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, and different websites may have different preferences.To maintain the singularity of the core responsibilities of the filter, and to avoid forcing UI/UX behaviors that may not meet the needs of all users in the default behavior, designers usually leave such features to developers to customize through JavaScript or at the template level, or to provide a unified global setting 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"The external link's security enhancement measures:
noopener: Prevent the new opened page from accessing the original page.window.openerThis 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 opened.RefererThis can protect user privacy, avoiding the disclosure of source information that jumps from your website to other websites. Add themVery necessaryIt can effectively prevent some phishing attacks and privacy leakage issues, improving the security of your website.
Q3: How can I make external links in a specific area (such as the main text of the article) open in a new window instead of the entire site?
A3:If you only want to target a specific area on the page (such as, only the article content section), you can put 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').So, JavaScript will only search and modify the links within this specific area.The same principle applies to any container with a specific ID or CSS class.