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:
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 named
base.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.paste JavaScript code:Copy the provided JavaScript code. Then, in
base.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>Save and clear cache:Save to
base.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.